Convert timedelta to Years in Python (2 Examples)

 

In this tutorial, I’ll illustrate how to express a timedelta in years in the Python programming language.

The post is structured as follows:

Let’s start right away!

 

Example Data & Imported Libraries

In the examples, we need the datetime module and the pandas library, so let’s first import them.

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

Besides that, for the demonstration, we need a sample data as defined below.

dt1 = datetime.datetime(2017, 1,  4)              # date_1 initialization
print(dt1)                                        # printing date_1
# 2017-01-04 00:00:00
 
dt2 = datetime.datetime(2022, 1, 18)              # date_2 initialization
print(dt2)                                        # printing date_2
# 2022-01-18 00:00:00

Now we can create a DataFrame utilizing the pandas library. See the following line.

df = pd.DataFrame({"dt1" : [dt1], "dt2": [dt2]})  # DataFrame Construction for Example 2

 

Example 1: Difference Between Two datetime Objects

This example demonstrates how to get the year difference between two datetime objects using the year attribute.

print(dt2.year - dt1.year)
# 5

 

Example 2: Difference via to_period() Function

This example shows how to utilize the o_period() function of the pandas library to solve our problem. The function is a trimmer that gets rid of the unnecessary parts of a date and returns the index number with respect to the given parameter.

For example, in this case by setting “Y” as the parameter, only the year indices will be extracted, and subtracted from each other.

print((df["dt2"].dt.to_period('Y').astype(int) - df["dt1"].dt.to_period('Y').astype(int)).values[0])
# 5

 

Video, Further Resources & Summary

Do you need further information on the topics of this tutorial? Then you might want to watch the following video on my YouTube channel. In the video, I’m explaining the Python codes of this article.

 

The YouTube video will be added soon.

 

In addition, you could have a look at the related posts on this homepage. You can find some tutorials on similar topics such as character strings and data conversion below:

 

Summary: In this Python tutorial, you have learned how to calculate the time difference in years. Please let me know in the comments section, if you have additional comments and/or questions.

 

Ö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 information 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