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



我想在下面逐一计算时差

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

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 

有一种方法:

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

成对迭代函数来自Python

中的:Iterate a list as pair (current, next)

希望对你有帮助。

相关内容

  • 没有找到相关文章

最新更新