如何将 timedelta 转换为字符串并再次返回

How to convert a timedelta to a string and back again

Dateutil 的 timedelta 对象似乎有一个自定义 __str__ 方法:

In [1]: from datetime import timedelta

In [2]: td = timedelta(hours=2)

In [3]: str(td)
Out[3]: '2:00:00'

我想做的是从其字符串表示中重新创建一个 timedelta 对象。然而,据我所知,datetime.parser.parse 方法将始终 return 一个 datetime.datetime 对象(参见 https://dateutil.readthedocs.io/en/stable/parser.html):

In [4]: import dateutil.parser

In [5]: dateutil.parser.parse(str(td))
Out[5]: datetime.datetime(2016, 11, 25, 2, 0)

我现在看到的唯一方法是,用 Convert a timedelta to days, hours and minutes 的说法,'bust out some nauseatingly simple (but verbose) mathematics' 获取秒、分钟、小时等,并将这些返回给__init__ 的新 timedelta。或者有没有更简单的方法?

模块 pytimeparse, which was inspired by How to construct a timedelta object from a simple string 似乎通过返回秒数来完成繁重的工作。我只是在它周围放了一个包装器,returns 一个具有相同秒数的 timedelta 对象:

#!/usr/bin/env python3.5
import datetime
import pytimeparse
import unittest

def reconstruct_timedelta(td_string):
    seconds = pytimeparse.parse(td_string)
    return datetime.timedelta(seconds=seconds)

class TestReconstruction(unittest.TestCase):
    def test_reconstruct_timedelta_is_inverse_of_str(self):
        td = datetime.timedelta(weeks=300, days=20, hours=3, minutes=4, milliseconds=254, microseconds=984)
        td_reconstructed = reconstruct_timedelta(str(td))
        self.assertTrue(td == td_reconstructed)

if __name__ == "__main__":
    unittest.main()

从测试中可以看出,重构的timedelta对象与原始对象相同,即使它是用任意数字初始化的millisecondsmicroseconds .

用 pickle 怎么样?您可以参考https://docs.python.org/2/library/pickle.html 序列化时间增量对象,稍后取回对象。

import pickle 

tdi = pickle.dumps(td)

tdo = pickle.loads(tdi) # will have the time delta object 

str(tdo) 

使用datetime.strptime将字符串转换为timedelta。

import datetime

td = datetime.timedelta(hours=2)

# timedelta to string
s = str(td) # 2:00:00

# string to timedelta
t = datetime.datetime.strptime(s,"%H:%M:%S")
td2 = datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)