How to convert X min, Y sec string to timestamp

Viewed 46

I have a dataframe with a duration column of strings in a format like:

index duration
0 26 s
1 24 s
2 4 min, 37 s
3 7 s
4 1 min, 1 s

Is there a pandas or strftime() / strptime() way to convert the duration column to a min/sec timestamp.

I've attempted this way to convert strings, but I'll run into multiple scenarios after replacing strings:

for row in df['index']:
    if "min, " in df['duration'][row]:
        df['duration'][row] = df['duration'][row].replace(' min, ', ':').replace(' s', '')
    else:
        pass

Thanks in advance

1 Answers

Try:

pd.to_timedelta(df['duration'])

Output:

0   0 days 00:00:26
1   0 days 00:00:24
2   0 days 00:04:37
3   0 days 00:00:07
4   0 days 00:01:01
Name: duration, dtype: timedelta64[ns]
Related