How To Convert Standard Timedelta String To Timedelta Object
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.82
Solution 1:
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
defparse(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.
Solution 2:
This is an update of Ray's answer that works for Python 3. It will return an empty string if the regex is fed a bad string for parsing, otherwise a timedelta object is returned.
from datetime import timedelta
import re
defparse_timedelta(stamp):
if'day'in stamp:
m = re.match(r'(?P<d>[-\d]+) day[s]*, (?P<h>\d+):'r'(?P<m>\d+):(?P<s>\d[\.\d+]*)', stamp)
else:
m = re.match(r'(?P<h>\d+):(?P<m>\d+):'r'(?P<s>\d[\.\d+]*)', stamp)
ifnot m:
return''
time_dict = {key: float(val) for key, val in m.groupdict().items()}
if'd'in time_dict:
return timedelta(days=time_dict['d'], hours=time_dict['h'],
minutes=time_dict['m'], seconds=time_dict['s'])
else:
return timedelta(hours=time_dict['h'],
minutes=time_dict['m'], seconds=time_dict['s'])
Post a Comment for "How To Convert Standard Timedelta String To Timedelta Object"