datetime to timedelta in pandas DataFrame & Vice Versa in Python (Examples)

 

In this article you’ll learn how to convert datetime to timedelta in a pandas DataFrame and vice versa in the Python programming language.

The tutorial looks as follows:

Here’s how to do it:

 

Example Data & Libraries

First, let’s load the pandas library and the datetime module:

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

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

df = pd.DataFrame.from_dict({"col_1" : [datetime.datetime(2000, 10, 8, 15, 21, 5),  # DataFrame initialization
                                        datetime.datetime(2005, 2, 8, 18, 21, 5),
                                        datetime.datetime(2010, 5, 8, 3, 10, 19),
                                        datetime.datetime(2017, 7, 8, 8, 4, 2)]})
print(df)                                                                           # printing DataFrame
#                col_1
#0 2000-10-08 15:21:05
#1 2005-02-08 18:21:05
#2 2010-05-08 03:10:19
#3 2017-07-08 08:04:02

Since we have our DataFrame of datetime objects, we can move on to the examples now.

 

Example 1: Convert a Column of datetime Objects to timedelta

Since the timedelta objects are meant to show the difference between two dates, first we need to create a datetime object for a random date. See dt_origin below.

dt_origin = datetime.datetime(2000, 1, 1, 0, 0, 0)                                  # start_date initialization

Now we can simply define our function which subtracts the two datetime objects to generate a timedelta object.

def datetime_to_timedelta(dt):                                                      # defining the dt to td function
    return dt - dt_origin                                                           # generating and returning the timedelta object

After defining our function, we can plug it into the apply() function to convert the datetime objects in col_1 to the timedelta objects in col_2.

df["col_2"] = df["col_1"].apply(lambda dt: datetime_to_timedelta(dt))               # creating the column of timedelta objects
print(df)                                                                           # printing the updated DataFrame
#                col_1              col_2
#0 2000-10-08 15:21:05  281 days 15:21:05
#1 2005-02-08 18:21:05 1865 days 18:21:05
#2 2010-05-08 03:10:19 3780 days 03:10:19
#3 2017-07-08 08:04:02 6398 days 08:04:02

 

Example 2: Convert a Column of timedelta Objects to datetime

In this case, we do the same thing but in reverse order. We add dt_origin to the td values to get the datetime objects in the beginning.

def timedelta_to_datetime(td):                                                      # defining the td to dt function
    dt = dt_origin + td                                                             # generating the datetime object
    return dt                                                                       # returning the datetime object

After defining the function timedelta_to_datetime(), we can plug it into the apply() function to convert the timedelta objects in col_2 to the datetime objects in col_3. Please be aware that we obtained an identical column with column col_1.

df["col_3"] = df["col_2"].apply(lambda td: timedelta_to_datetime(td))               # creating the column of timedelta objects
print(df)                                                                           # printing the updated DataFrame
#                col_1              col_2               col_3
#0 2000-10-08 15:21:05  281 days 15:21:05 2000-10-08 15:21:05
#1 2005-02-08 18:21:05 1865 days 18:21:05 2005-02-08 18:21:05
#2 2010-05-08 03:10:19 3780 days 03:10:19 2010-05-08 03:10:19
#3 2017-07-08 08:04:02 6398 days 08:04:02 2017-07-08 08:04:02

 

Video, Further Resources & Summary

Do you need further information on the Python programming codes of this article? Then you may want to have a look at the following video on my YouTube channel. I demonstrate the Python programming codes of this tutorial in the video.

 

The YouTube video will be added soon.

 

Furthermore, you might want to have a look at some of the other tutorials on my website:

 

In summary: In this tutorial, I have explained how to transform datetime objects to timedelta objects in a pandas DataFrame and back in the Python programming language. Don’t hesitate to let me know in the comments below, in case you have any additional 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 more 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