Consider this snippet
In[1]: import pandas as pd
In[2]: str(pd.to_timedelta("1354s"))
Out[2]: '0 days 00:22:34'
I would prefer the format
'22:34'
instead, since there is 0 hours and 0 days.
How can I demand such a 'most compact representation' ?
EDIT: More examples.
In[3]: [ str(pd.to_timedelta(t,unit='s')) for t in [10,1000,10000]]
Out[3]: ['0 days 00:00:10', '0 days 00:16:40', '0 days 02:46:40']
But I would like to get
['10', '16:40', '2:46:40']
or maybe
['10s', '16m 40s', '2h 46m 40s']
or something along those lines
EDIT:
The linked dupe suggest that one should - at least in the case of python standard timedeltas - create a custom formatter. I decided to go like this:
def pd_td_fmt(td):
import pandas as pd
assert isinstance(td, pd.Timedelta)
abbr = {'days': 'd', 'hours': 'h', 'minutes': 'min', 'seconds': 's', 'milliseconds': 'ms', 'microseconds': 'us',
'nanoseconds': 'ns'}
return "".join(f"{v}{abbr[k]}" for k, v in td.components._asdict().items() if v != 0)
With output example:
[ pd_td_fmt(pd.to_timedelta(t,unit='s')) for t in [10,1000,10000]]
Out[9]: ['10s', '16min40s', '2h46min40s']