What is the simplest way to convert standard timedelta string to timedelta object?
I have printed several timedelta objects and got these strings:
'1157 days, 9:46:39'
'12:00:01.824952'
'-1 day, 23:59:31.859767'
I know I could write parser myself, but is there any simpler solution?
I cannot find a better way other than writing a parser myself. The code looks bulky but it is essentially parsing string into a dictionary which is useful not only to creating a timedelta object.
import re
def parse(s):
if 'day' in s:
m = re.match(r'(?P<days>[-\d]+) day[s]*, (?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d[\.\d+]*)', s)
else:
m = re.match(r'(?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d[\.\d+]*)', s)
return {key: float(val) for key, val in m.groupdict().iteritems()}
Test:
from datetime import timedelta
s1 = '1157 days, 9:46:39'
s2 = '12:00:01.824952'
s3 = '-1 day, 23:59:31.859767'
t1 = parse(s1)
t2 = parse(s2)
t3 = parse(s3)
timedelta(**t1) # datetime.timedelta(1157, 35199)
timedelta(**t2) # datetime.timedelta(0, 43201, 824952)
timedelta(**t3) # datetime.timedelta(-1, 86371, 859767)
Hope this can suit your purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With