How Do I Format a pandas timedelta object?

Question:

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?

Asked By: psychemedia

||

Answers:

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

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

Answered By: psychemedia

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}'
Answered By: Hunaphu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.