Calculate Timedelta Using pandas.Series.dt.to_period() function
pandas.Series.dt.to_period() function:
Syntax:
Series.dt.to_period(*args, **kwargs)
converts datetime array to period array.
parameters:
freq= optional value, offset string or offset object
In this example, we read the time.csv and convert values in each column to DateTime. after converting columns to DateTime we use pandas.Series.dt.to_period() to calculate time delta in months. ‘M’ string in to_period() function symbolizes months. Month-end objects are returned.
CSV Used:
Python3
# import packages and libraries import pandas as pd # reading the csv file data = pd.read_csv( 'time.csv' ) # converting columns to datetime data[ 'start_date' ] = pd.to_datetime(data[ 'start_date' ]) data[ 'end_date' ] = pd.to_datetime(data[ 'end_date' ]) # calculating time delta in months data[ 'time_delta_months' ] = data[ 'end_date' ].dt.to_period( 'M' ) - \ data[ 'start_date' ].dt.to_period( 'M' ) print (data) |
Output:
How to Calculate Timedelta in Months in Pandas
The difference between two dates or times is represented as a timedelta object. The duration describes the difference between two dates, datetime, or time occurrences, while the delta means an average of the difference. One may estimate the time in the future and past by using timedelta. This difference between two dates when calculated in terms of months, it’s called time delta in months. Let’s demonstrate a few ways to calculate the time delta in months in pandas.