如何将标准timedelta字符串转换为timedelta对象

时间:2014-01-12 11:32:49

标签: python datetime

将标准timedelta字符串转换为timedelta对象的最简单方法是什么?

我已经打印了几个timedelta对象并获​​得了这些字符串:

'1157 days, 9:46:39'
'12:00:01.824952'
'-1 day, 23:59:31.859767'

我知道我自己可以编写解析器,但有没有更简单的解决方案?

2 个答案:

答案 0 :(得分:5)

除了自己编写解析器之外,我找不到更好的方法。代码看起来很笨重但它本质上是将字符串解析为字典,这不仅对创建timedelta对象很有用。

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()}

测试:

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)

希望这可以满足您的目的。

答案 1 :(得分:1)

这是对适用于 Python 3 的 Ray 答案的更新。如果正则表达式被提供用于解析的错误字符串,它将返回一个空字符串,否则返回一个 timedelta 对象。

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'])