Convert pandas timedeltas to seconds, minutes and hours

Create Example Data

We will start by creating a very simple DataFrame that you can use in order to followi along this detailed example.

import pandas as pd

participant = ['Joe', 'Eric', 'Aaron']

duration = [pd.Timedelta(hours =  2, minutes = 15, seconds = 15) ,
            pd.Timedelta(hours =  2, minutes = 45, seconds = 10), 
            pd.Timedelta(hours =  2, minutes = 53, seconds = 22)]

#create DataFrame
times_df = pd.DataFrame ( dict(participant=participant, duration = duration))

print (times_df.head())

This snippet will return the following DataFrame – note that the duration column type is timedelta[ns64].

0Joe0 days 02:15:15
1Eric0 days 02:45:10
2Aaron0 days 02:53:22

Series of Timedeltas to seconds (integers and floats)

You can use the Series dt accessor and the total_seconds function to convert your column of timedeltas to seconds.

Floats: Note the use of the round() function:

times_df['duration_seconds'] = times_df['duration'].dt.total_seconds().round()

Note: make sure you use the dt accessor and don’t apply the total_seconds() function on the Series directly. Failing to do will raise the following exception:

AttributeError: 'Series' object has no attribute 'total_seconds'


times_df['duration_seconds'] = times_df['duration'].dt.total_seconds().astype('int64')

Note: An alternative was to accomplish this task is to use the apply method with a lambda function. Be aware that using a vector operation as shown above is way faster though:

times_df['duration_seconds'] = times_df['duration'].apply (lambda cell: cell.total_seconds())

Convert timedeltas to hours and minutes

Using a similar logic we can turn the delta into a number of minutes.

times_df['duration_minutes'] = (times_df['duration'].dt.total_seconds()/60).round(2)

And to hours:

times_df['duration_hours'] = (times_df['duration'].dt.total_seconds()/3600).round(2)

Here’s our DataFrame:

0Joe0 days 02:15:158115135.252.25
1Eric0 days 02:45:109910165.172.75
2Aaron0 days 02:53:2210402173.372.89

Follow up learning

How to cast a datetime column in pandas to find the day of the week?