Calculate Timedelta using a user-defined function
Instead of using built-in functions, we can use our own user-defined function pd.Timestamp() function converts DateTime-like, str, int, or float time object to timestamp. Then we extract year and month values from the timestamps. as each year has 12 months we multiply 12 with the year difference and add the month difference.
Python3
# import packages and libraries import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # creating a dataframe data = pd.DataFrame({ 'startdate' : [pd.Timestamp( '20181211' ), pd.Timestamp( '20180701' )], 'enddate' : [pd.Timestamp( '20190612' ), pd.Timestamp( '20190712' )]}) def time_delta_month(end, start): return 12 * (end.dt.year - start.dt.year) \ + (end.dt.month - start.dt.month) print (time_delta_month(data[ 'enddate' ], data[ 'startdate' ])) |
Output:
0 6 1 12 dtype: int64
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.
Contact Us