Hamid K
Hamid K

Reputation: 1165

Convert consecutive time difference (timedelta) to seconds

I calculated my consecutive time difference in my DataFrame of d using:

d['delta'] = (d['time'] - d['time'].shift()).fillna(0)

So I have the time difference in 'delta' column. My question is how can I convert that to seconds? The output is in the format of 00:50:00, I want to convert that to 3000 seconds.

Upvotes: 2

Views: 1995

Answers (1)

Alex Riley
Alex Riley

Reputation: 177048

Your column is of timedelta64 type so you can use the .dt accessor to find the seconds property:

d['delta'].dt.seconds

More information about the .dt accessor can be found here.


As @Jeff points out in the comments, you're likely to be better off using total_seconds() instead of seconds; the latter only returns whole (integer) numbers of seconds (modulo 1 day == 86400 seconds) whereas the former will return float values, counting smaller units of time (ms, ns) as well as days towards the value:

d['delta'].dt.total_seconds()

Upvotes: 4

Related Questions