我试图找出一种方法来查找此列表中连续项目之间的时间延迟。
L1=[['8/1/2000', '0:00:16'],
['8/1/2008', '0:23:09'],
['8/2/2008', '12:32:16'],
['8/2/2008', '0:38:29']]
因此输出看起来像1和2 = 0:22:53之间的差异,但2和3之间的差异需要24小时+/-差异而不仅仅是0:06:58。希望这是有道理的。任何帮助表示赞赏。
答案 0 :(得分:1)
由于这似乎是一个蠢蠢欲动的问题,我只是简单地指出你datetime模块的方向,给出一个例子,剩下的给你。
首先,我们会将您的字符串(或我们认为是字符串的字符串)转换为日期时间对象:
>>> from datetime import datetime
>>> L1 = [['8/1/2000', '0:00:16'], ['8/1/2008', '0:23:09'], ['8/2/2008', '12:32:16'], ['8/2/2008', '0:38:29']]
>>> d1 = [datetime.strptime(' '.join(dt), '%m/%d/%Y %H:%M:%S') for dt in L1]
>>> d1
[datetime.datetime(2000, 8, 1, 0, 0, 16), datetime.datetime(2008, 8, 1, 0, 23, 9), datetime.datetime(2008, 8, 2, 12, 32, 16), datetime.datetime(2008, 8, 2, 0, 38, 29)]
>>> for d in d1:
... print(d)
...
2000-08-01 00:00:16
2008-08-01 00:23:09
2008-08-02 12:32:16
2008-08-02 00:38:29
这些我们可以简单地减去,生成timedelta对象:
>>> diffs = [y-x for x,y in zip(d1, d1[1:])]
>>> diffs
[datetime.timedelta(2922, 1373), datetime.timedelta(1, 43747), datetime.timedelta(-1, 43573)]
>>> for diff in diffs:
... print(diff)
...
2922 days, 0:22:53
1 day, 12:09:07
-1 day, 12:06:13