Title: Add to/from string methods to datetime.timedelta
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.10
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: belopolsky, eric.smith, martin.panter, p-ganssle, tebeka
Priority: normal Keywords:

Created on 2020-07-09 06:46 by tebeka, last changed 2020-07-20 17:15 by p-ganssle.

Messages (4)
msg373380 - (view) Author: Miki Tebeka (tebeka) * Date: 2020-07-09 06:46
I suggest adding datetime.timedelta methods that convert to/from str.

The reason is that I have several places where configuration contains various timeouts. I'd like to write '50ms' and not 0.05 which is more human readable.

See for how Go does it.
msg373400 - (view) Author: Martin Panter (martin.panter) * (Python committer) Date: 2020-07-09 13:02
I don't know how much support this will get since there is already a str(timedelta) operation defined with a different format. But I don't like that format much. The day[s] part is too verbose, the H:MM:SS part could too easily be interpreted as D:HH:MM, and the result for negative deltas is horrible (-43 days, 23:59:55; see Issue 38701).

My favourite format for a duration is usually the HTML 5 format like

1w 0d 12h 0m 27s

Another option is ISO 8601 format:


But both of these standards only go down to the seconds unit, so 50 ms has to be 0.05s or PT0.05S.
msg373439 - (view) Author: Miki Tebeka (tebeka) * Date: 2020-07-10 03:59
I think the lack sub second parts in these formats is a disadvantage.
There's a merit in using a standard but IMO it's more natural to write someting like "2s" in a configuration value than "P2S" which is more cryptic.
msg374017 - (view) Author: Paul Ganssle (p-ganssle) * (Python committer) Date: 2020-07-20 17:15
I think it is unlikely that we'll want to experiment with this directly in CPython. I don't think a fixed format (other than the annoying one that you already get from calling `str` on a timedelta) is appropriate, but designing a modular format for time differences is more complicated than it might seem. I have had an open issue on dateutil to implement this for ages, but I haven't seen or come up with any proposals for a DSL for specifying timedelta formats:

It is annoyingly complicated to do this, and I'd rather it be tried out in other libraries with more flexibility to make breaking changes and a shorter release cadence. Dateutil is a good choice, but a clear and thorough proposal (or at least examples of this done well in other ecosystems we can crib from) is necessary.
Date User Action Args
2020-07-20 17:15:48p-gansslesetmessages: + msg374017
2020-07-10 03:59:03tebekasetmessages: + msg373439
2020-07-09 13:02:49martin.pantersetnosy: + martin.panter
messages: + msg373400
2020-07-09 07:30:00eric.smithsetnosy: + eric.smith
2020-07-09 07:10:44xtreaksetnosy: + belopolsky, p-ganssle

versions: + Python 3.10
2020-07-09 06:46:58tebekacreate