8

I am using pandas timedelta objects to keep track of split times in a sports related data set using the following sort of construction:

import pandas as pd
pd.to_timedelta("-0:0:1.0")

This natively reports as:

-1 days +23:59:59

I can get the raw seconds count using pd.to_timedelta("-0:0:1.0").total_seconds() but that is unwieldy where the negative amount is in minutes or hours:

For the expression:

pd.to_timedelta("-1:2:3.0")

how can I get the report formatted as"-1:2:3.0, or -1 hour, 2 minutes, 3 seconds, from the timedelta object, rather than in the form -3723.0000000000005 (with a float error) or -1 days +22:57:57?

Luke
  • 1,741
  • 10
  • 29
psychemedia
  • 5,320
  • 5
  • 48
  • 81

3 Answers3

2

See the function strfdelta(tdelta, fmt) provided as an answer to a related question: https://stackoverflow.com/a/8907269/454773

Community
  • 1
  • 1
psychemedia
  • 5,320
  • 5
  • 48
  • 81
1

Is that what you want?

In [223]: df
Out[223]:
              delta
0 -1 days +23:59:59
1 -1 days +22:57:57
2          00:00:11

In [224]: df.delta.abs().dt.components
Out[224]:
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     0      0        0        1             0             0            0
1     0      1        2        3             0             0            0
2     0      0        0       11             0             0            0
MaxU - stop genocide of UA
  • 191,778
  • 30
  • 340
  • 375
  • Doh! Okay, yes.. if negative take the absolute. The components method is handy too... What I was really looking for was a way of controlling the display format of the the delta object directly using something like `strftime` formatting. – psychemedia Jan 22 '17 at 14:22
1

Here is a sad solution that works well.

(pd.to_datetime('2262-04-11') + mydelta).strftime('%H:%M')
Hunaphu
  • 385
  • 6
  • 7