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].
participant | duration | |
---|---|---|
0 | Joe | 0 days 02:15:15 |
1 | Eric | 0 days 02:45:10 |
2 | Aaron | 0 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'
Integers:
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:
times_df.head()
participant | duration | duration_seconds | duration_minutes | duration_hours | |
---|---|---|---|---|---|
0 | Joe | 0 days 02:15:15 | 8115 | 135.25 | 2.25 |
1 | Eric | 0 days 02:45:10 | 9910 | 165.17 | 2.75 |
2 | Aaron | 0 days 02:53:22 | 10402 | 173.37 | 2.89 |
Follow up learning
How to cast a datetime column in pandas to find the day of the week?