How to return total time in seconds given a column with only hour-minute-second format

Question:

I have a pandas DataFrame with a column with 00:00:00 (hour, minute, second) format.

import pandas as pd

# sample dataframe
df = pd.DataFrame({'Time': ['00:01:00', '00:00:30', '00:01:30', '00:00:10']})

       Time
0  00:01:00
1  00:00:30
2  00:01:30
3  00:00:10

I need to create a column with the total seconds in the column. How can I achieve this?

       Time  Time in secs
0  00:01:00          60.0
1  00:00:30          30.0
2  00:01:30          90.0
3  00:00:10          10.0

I tried:

df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S')

But this results in the following, which does not match the expected output.

       Time        Time in secs
0  00:01:00 1900-01-01 00:01:00
1  00:00:30 1900-01-01 00:00:30
2  00:01:30 1900-01-01 00:01:30
3  00:00:10 1900-01-01 00:00:10
Asked By: Alex

||

Answers:

You don’t have a date, so easiest to work with Timedelta, and your format matches exactly what is required. These have exactly the attribute you want: total_seconds

pd.to_timedelta(df.Time).dt.total_seconds()
#0    60.0
#1    30.0
#2    90.0
#3    10.0
#Name: Time, dtype: float64
Answered By: ALollz

Convert the time column to a timedelta and divide it by seconds

df['Time in secs'] = pd.to_timedelta(df['Time'])/pd.to_timedelta(1, unit='S')

result

df['Time in secs']
0    60.0
1    30.0
2    90.0
3    10.0
Name: Time, dtype: float64
Answered By: pythonic833
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.