Search code examples
pandasdurationtimedeltadelta

Duration to Seconds in Pandas


How can i a Series like this:

2016-11-09 00:07:00    0 days 00:00:15.000000000
2016-11-09 00:07:15    0 days 00:20:14.000000000
2016-11-09 00:07:30    0 days 10:00:15.000000000

into in integer values like this:

2016-11-09 00:07:00    15
2016-11-09 00:07:15    1214 // 20*60+14
2016-11-09 00:07:30    36015 // 10*60*60+15

Solution

  • Those are TimeDeltas. You should be able to use the total_seconds method. However, you'd need to access that method via the datetime accessor dt. Assuming your series is named s

    s.dt.total_seconds()
    
    2016-11-09 00:07:00       15.0
    2016-11-09 00:07:15     1214.0
    2016-11-09 00:07:30    36015.0
    dtype: float64
    

    Hower, if by chance those are strings. It might be better to do use pd.to_timedelta

    pd.to_timedelta(s).dt.total_seconds()
    
    2016-11-09 00:07:00       15.0
    2016-11-09 00:07:15     1214.0
    2016-11-09 00:07:30    36015.0
    dtype: float64