# Datetime.timedelta.\_\_format\_\_?

**URL:** <https://discuss.python.org/t/datetime-timedelta-format/6219>\
**Category:** Ideas\
**Created:** [December 17, 2020, 2:55pm UTC](https://discuss.python.org/t/datetime-timedelta-format/6219 "2020-12-17T14:55:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![eumiro](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/eumiro/32/3123_2.png) [@eumiro](https://discuss.python.org/u/eumiro)\
**Post date:** [December 17, 2020, 2:55pm UTC](https://discuss.python.org/t/datetime-timedelta-format/6219/1 "2020-12-17T14:55:15Z")

</div>

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:

```auto
>>> 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.

---

<div class="post-metadata">

**Author:** ![daniele](https://avatars.discourse-cdn.com/v4/letter/d/dfb087/32.png) [@daniele](https://discuss.python.org/u/daniele)\
**Post date:** [December 17, 2020, 7:42pm UTC](https://discuss.python.org/t/datetime-timedelta-format/6219/2 "2020-12-17T19:42:30Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![eumiro](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/eumiro/32/3123_2.png) [@eumiro](https://discuss.python.org/u/eumiro)\
**Post date:** [December 17, 2020, 8:23pm UTC](https://discuss.python.org/t/datetime-timedelta-format/6219/3 "2020-12-17T20:23:43Z")

</div>

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