'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.824952'
'-1 day, 23:59:31.859767'
I know I could write parser myself, but is there any simpler solution?
Solution 1:[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
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.
Solution 2:[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
def parse_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)
if not 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'])
Solution 3:[3]
If you are using Django, you could do
from django.utils.dateparse import parse_duration
parse_duration('-1 day, 23:59:31.859767')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Ramast |
