Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert timedelta hh:mm to seconds

I can't seem to find this anywhere but I'm trying to convert timestamps expressed as hh:mm to total seconds.

d = ({
    'A' : ['08:00','08:10','08:12','08:26','08:29','08:31','10:10','10:25','10:29','10:31'],
    })

df = pd.DataFrame(data=d)

If the timestamps were expressed as hh:mm:ss I would use the following:

secs = (pd.to_timedelta(df['A']).dt.total_seconds())

But when I try this on hh:mm I get an error?

ValueError: expected hh:mm:ss format.

Is there a simple way to convert time when displayed as hh:mm


2 Answers

Just append :00 to the end of the string to convert it in the format hh:mm:ss.

Ex: 08:00 could be rewritten as 08:00:00

Quick way to fix this:

d['A'] = [x + ':00' for x in d['A']]

And then, you can run the following:

secs = (pd.to_timedelta(d['A']).dt.total_seconds())
like image 180
Melvin Abraham Avatar answered Dec 04 '25 23:12

Melvin Abraham


You can add seconds also in this way:

df['A'] = pd.to_datetime(df['A']).dt.strftime('%H:%M:%S')

Output:

         A
0  08:00:00
1  08:10:00
2  08:12:00
3  08:26:00
4  08:29:00
5  08:31:00
6  10:10:00
7  10:25:00
8  10:29:00
9  10:31:00
like image 39
Joe Avatar answered Dec 05 '25 00:12

Joe