Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
niekas Avatar asked Jan 12 '14 11:01

niekas


1 Answers

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.

like image 67
Ray Avatar answered Oct 10 '22 06:10

Ray