I was looking for a simple intuitive way to parse a timedelta from a string. 
The best I could find feels clunky at best: 
https://stackoverflow.com/questions/4628122/

Solution 1 looks like this:
```
from datetime import datetime, timedelta
t = datetime.strptime('05:20:25', '%H:%M:%S')
delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
```

Solution 2 looks like this:
```
from datetime import datetime, timedelta
t = datetime.strptime('05:20:25', '%H:%M:%S')
delta = t - datetime.combine(t.date(), time.min)
```

Solution 3 looks like this:
```
from datetime import timedelta
import re
match = re.match(r'(?P<hours>\d{2}):(?P<minutes>\d{2}):(?P<seconds>\d{2})', 
'05:20:25')
delta = timedelta(**match.groupdict())
```

Formatting back to strings is as verbose:
```
string = f'{delta.hours:02d}:{delta.minutes:02d}:{delta.seconds:02d}'

I think it would be nicer and more intuitive if timedelta had strptime and 
strftime like datetime has.
```
delta = timedelta.strptime('05:20:25', '%H:%M:%S')  # timedelta(hours=5, 
minutes=20, seconds=25)
string = delta.strftime('%H:%M:%S')  # '05:20:25'
```

The reason I would like this in the standard lib (vs maintaining my own 
helpers) is that :
    a) it feels very natural, especially after years of using these methods on 
datetime.
    b) there's currently three ways to do it that I've seen in the wild 
(documented above). Having this in the std lib would help with the ZoP "There 
should be one-- and preferably only one --obvious way to do it." (the "obvious" 
part of this statement is covered in (a)).

I'm sure there's corner cases I'm not seeing that make this more complicated to 
implement than it seems... Let me know.

Cheers,

Thomas
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/CTIEDFKW5ITOXUHVCZZLPDCFJJAXZODV/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to