1

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']
LudvigH
  • 3,662
  • 5
  • 31
  • 49
  • what if you have more than 59 minutes? – FObersteiner Nov 12 '20 at 09:21
  • Then please add the hour information in the string. Ill update the question to clarify! – LudvigH Nov 12 '20 at 09:22
  • I think you can create a suitable function from [this answer](https://stackoverflow.com/a/13756038/10197418) from the linked dupe. – FObersteiner Nov 12 '20 at 09:28
  • @MrFuppes I don't consider it a dupe, since one is referring to `datetime.timedelta`, and the other refers to `pandas.Timedelta`. But sure.... I could roll my own formatter... Even though that is a terrible mess... – LudvigH Nov 12 '20 at 09:31
  • pandas.Timedelta "behaves" pretty much the same as datetime.timedelta. If you don't give too much about the aesthetics, you can use something more simple, e.g. like [this](https://stackoverflow.com/a/64662985/10197418). – FObersteiner Nov 12 '20 at 09:39
  • Ok. Thanks. I decided to go via `.components` to avoid doing the math myself. That is - by the way - not available on the standard timedelta object, so it also highlights the non-dupe-ness of my question. – LudvigH Nov 12 '20 at 09:51
  • that's a good point; you'd have to write an attribute getter for the standard timedelta. if you come up with a good function, I think this could be useful for others; so why not add an answer to the linked question? I'd give it a +1 ^^ – FObersteiner Nov 12 '20 at 10:00
  • Ah! Now more appropriate dupes have been found, and in one of them, someone actually do use `.components`. So I have to resign this question as a dupe. Thanks anyway! – LudvigH Nov 12 '20 at 10:04

0 Answers0