如何以小时 - 分钟 - 秒格式轻松计算时差

时间:2014-03-10 06:12:11

标签: python datetime python-2.7 python-datetime

我想在下面逐一计算时差。

如何以简单的方式获得它?

00:00:01.97-00:00:01.43 = 0.44 (unit:second)

数据

00:00:01.43
00:00:01.97
00:00:02.50
00:00:03.04
00:00:03.54 
00:00:04.04 
00:00:04.57 
00:00:05.11 
00:00:05.61 
00:00:06.14 
00:00:06.64 
00:00:07.14 
00:00:07.64 
00:00:08.18 
00:00:08.68 
00:00:09.18 
00:00:09.21 

1 个答案:

答案 0 :(得分:1)

这是一种方法:

from datetime import datetime
import itertools


data = """00:00:01.43
00:00:01.97
00:00:02.50
00:00:03.04
00:00:03.54
00:00:04.04
00:00:04.57
00:00:05.11
00:00:05.61
00:00:06.14
00:00:06.64
00:00:07.14
00:00:07.64
00:00:08.18
00:00:08.68
00:00:09.18
00:00:09.21"""


def pairs(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)


format = "%H:%M:%S.%f"
for before, after in pairs(data.split()):
    before_dt = datetime.strptime(before, format)
    after_dt = datetime.strptime(after, format)
    difference = (after_dt - before_dt).total_seconds()

    print "%s vs %s: %s" % (before, after, difference)

打印:

00:00:01.43 vs 00:00:01.97: 0.54
00:00:01.97 vs 00:00:02.50: 0.53
00:00:02.50 vs 00:00:03.04: 0.54
00:00:03.04 vs 00:00:03.54: 0.5
00:00:03.54 vs 00:00:04.04: 0.5
00:00:04.04 vs 00:00:04.57: 0.53
00:00:04.57 vs 00:00:05.11: 0.54
00:00:05.11 vs 00:00:05.61: 0.5
00:00:05.61 vs 00:00:06.14: 0.53
00:00:06.14 vs 00:00:06.64: 0.5
00:00:06.64 vs 00:00:07.14: 0.5
00:00:07.14 vs 00:00:07.64: 0.5
00:00:07.64 vs 00:00:08.18: 0.54
00:00:08.18 vs 00:00:08.68: 0.5
00:00:08.68 vs 00:00:09.18: 0.5
00:00:09.18 vs 00:00:09.21: 0.03

成对迭代函数取自:Iterate a list as pair (current, next) in Python

希望有所帮助。