python - How to calculate time difference easily in hour-minute-second format -
i want calculate time differences 1 one in following.
how in easy way ?
00:00:01.97-00:00:01.43 = 0.44 (unit:second)
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
here's 1 way it:
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" 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)
prints:
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
pairwise iterating function taken from: iterate list pair (current, next) in python
hope helps.
Comments
Post a Comment