String formatting of timedeltas in Pandas
Asked Answered
D

1

8

I noticed that Pandas knows how to smartly format a timedelta object into a string.

In [1]: df[column][rows].max()
Out[1]: 
0   2 days, 02:08:07
dtype: timedelta64[ns]

When I try to do this manually I keep getting the string in nanoseconds.

In [2]: df[column][rows].max()[0]
Out[2]: numpy.timedelta64(180487000000000,'ns')

In [2]: str(df[column][rows].max()[0])
Out[2]: '180487000000000 nanoseconds'

I would rather not reinvent the wheel, so is there any way to access the string formatting method (or the string itself) that Pandas uses to show a timedelta object in x days, hh:mm:ss ?

Diluvial answered 25/8, 2013 at 20:2 Comment(0)
G
7

The function is located here:

pd.tslib.repr_timedelta64

In action:

In [11]: pd.tslib.repr_timedelta64(np.timedelta64(180487000000000,'ns'))
Out[11]: '2 days, 02:08:07'
Gery answered 25/8, 2013 at 20:9 Comment(3)
May I ask, how did you know this was the function? Do you know the code base well? Pandas has some nice string formatting utilities, so it would be great to know how to browse them.Diluvial
I had a feeling it would be in tslib (as I know the code base, and that is where timeseries stuff is), and found it with a tab complete :)Gery
This solution got out-of-date and no longer works.Agadir

© 2022 - 2024 — McMap. All rights reserved.