Calculate Timedelta using months in integer

In the previous method, Monthends object is returned. If we want it to be in integer we have to convert it using the astype() function or by using view(dtype=’int64′). 

Python3




# import packages and libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
 
# 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').astype(int) - \
    data['start_date'].dt.to_period('M').astype(int)
 
# print(data)
print(data)


Output:

Example 2: Using .view(dtype=’int64′) to convert into integers

Python3




# import packages and libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
 
# 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').view(dtype='int64') -\
    data['start_date'].dt.to_period('M').view(dtype='int64')
 
# print(data)
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.

Similar Reads

Method 1: Calculate Timedelta Using pandas.Series.dt.to_period() function

pandas.Series.dt.to_period() function:...

Method 2: Calculate Timedelta using months in integer

...

Method 3:  Calculate Timedelta using a user-defined function

In the previous method, Monthends object is returned. If we want it to be in integer we have to convert it using the astype() function or by using view(dtype=’int64′)....

Contact Us