Convert timedelta to Months in Python (2 Examples)

 

In this Python tutorial, you’ll learn how to convert a timedelta to months.

Table of contents:

Let’s just jump right in…

 

Example Data & Imported Libraries

First, we need to import the datetime module and the pandas library.

import datetime                                                     # importing datetime module
import pandas as pd                                                 # importing pandas library

Next, let’s also construct some example data in Python:

dt1 = datetime.datetime(2017, 6,  5)                                # constructing sample datetime_1
print(dt1)                                                          # printing datetime_1
dt2 = datetime.datetime(2019, 8, 10)                                # constructing sample datetime_2
print(dt2)                                                          # printing datetime_2

 

Example 1: User-defined Function to Calculate Difference in Months

Our function basically gets the difference between the year and month attributes of the given datetime objects, then sums them up in terms of months.

def timedelta_in_months(end, start):                                # defining the function
    return 12 * (end.year - start.year) + (end.month - start.month) # returning the calculation

If we call the function and print the result, the following is obtained.

print(timedelta_in_months(dt2, dt1))                                # printing the month difference
# 26

 

Example 2: to_period() Function to Calculate Difference in Months

In this example, I’ll show how to calculate the difference by utilizing the to_period() function of the pandas library. For this example, we should convert the data to a pandas DataFrame as shown below.

df = pd.DataFrame({"dt1" : [dt1], "dt2": [dt2]})                    # constructing sample DataFrame
print(df)                                                           # printing the DataFrame
# dt1        dt2
#0 2017-06-05 2019-08-10

Now we can employ the to_period() function, which returns the date up to the time unit given by the parameter. In this case, it will return datetimes with the information of months and years only.

print(df["dt2"].dt.to_period('M'), df["dt1"].dt.to_period('M'))    # printing to_period results
# 2019-08, 2017-06

The advantage of the to_period() function is that it can calculate the datetime difference with respect to any time unit by a simple parameter change. For another use with a different parameter, see the tutorial Convert timedelta to Years in Python.

The calculation of the month difference can be seen below.

print(df["dt2"].dt.to_period('M').astype(int) 
      - df["dt1"].dt.to_period('M').astype(int))                   # printing the month difference
# 26

 

Video, Further Resources & Summary

Do you need more explanations on the contents of this tutorial? Then you may want to have a look at the following video on the Statistics Globe YouTube channel. I explain the Python programming code of this page in the video:

 

The YouTube video will be added soon.

 

Furthermore, you might have a look at the other posts on www.statisticsglobe.com.

 

This article has illustrated how to calculate the time difference in months in Python. Please let me know in the comments section below, if you have further questions. Besides that, don’t forget to subscribe to my email newsletter to get updates on the newest articles.

 

Ömer Ekiz Python Programming & Informatics

This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get further details about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top