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:
- units: year(?), month(?), week, day, hour, minute, second (milli/micro)second.
- the string can contain any of those units, even several times
- all the units are integers, only the smallest one can be float
- for negative timedeltas, only the biggest unit will be shown as negative
- 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.