Datetime.timedelta.__format__?

I am missing better formatting of the datetime.timedelta objects. str(td) contains the English word “day/days” and requires quite a lot of string manipulation to change. Another way is to extract total_seconds() and then combine divmod calls to get the right values for each time unit.

My proposal is to have some strftime/strptime grammar as follows:

  1. units: year(?), month(?), week, day, hour, minute, second (milli/micro)second.
  2. the string can contain any of those units, even several times
  3. all the units are integers, only the smallest one can be float
  4. for negative timedeltas, only the biggest unit will be shown as negative
  5. the units can be formatted as ints/floats, zero-padded, thousands-separators, etc.

Examples:

>>> f'{timedelta(seconds=1):%02S}'
'01'
>>> f'{timedelta(seconds=123):%02S}'
'123'
>>> f'{timedelta(seconds=123):%M:%02S}'
'2:03'
>>> f'{timedelta(seconds=123.456):%M:%02.1S}'
'2:03.5'
>>> f'{timedelta(days=1.234):%d jours, %.1H heures}'
'1 jours, 5.6 heures'
>>> f'{timedelta(days=1.234):%.2d jours, %.2H heures}'
ValueError(…)

If you find it a good idea, I’d create a GitHub repo to gather as many tests as possible. Looking forward to hearing from you.

I had a similar need a while ago and I solved it with a subclass implementing the __format__ dunder method. I can share the code, if you like, I don’t think it is published anywhere yet. It is not as general as you probably wish, but it can be easily adapted.

1 Like

Yes, Daniele, I’d like to see your code. I believe every stdlib’s class deserves a good documentation and good formatting options.