9

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?

The Singularity
  • 2,428
  • 3
  • 19
  • 48
psychemedia
  • 5,690
  • 7
  • 52
  • 84

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,690
  • 7
  • 52
  • 84
2

Here is a sad solution that works (but not for mydelta > 23:47:16.854775807).

(pd.to_datetime('2262-04-11') + mydelta).strftime('%H:%M')

Update

This works for larger mydelta but requires manual formatting.

y = mydelta.total_seconds()
h = 3600
tstr = f'{int(y/h)}:{int(y%h/60):02d}:{int(y%60):02d}'
Hunaphu
  • 589
  • 10
  • 11
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 - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
  • 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