2011-02-04 1091 views
4

我有一个“%H:%M:%S”格式的时间戳列表。例如Python:解析时间戳和计算时间差(以毫秒为单位)

09:50:08.650000 
    09:50:08.665000 
    09:50:08.820000 
    09:50:08.877000 
    09:50:09.897000 
    09:50:09.907000 
    09:50:09.953000 
    09:50:10.662000 
    09:50:10.662000 

我需要在python中有效地计算每行之间的时间差(以毫秒为单位)。

+0

格式为'%H:%M:%S.%f'。 – eumiro 2011-02-04 14:08:55

+0

我明白了。谢谢。我现在有一个timedelta表示。我如何计算以毫秒为单位的差异? – LouisChiffre 2011-02-04 14:11:13

+2

`int(diff.seconds * 1000. + diff.microseconds/1000.)` – eumiro 2011-02-04 14:12:14

回答

7

%H:%M:%S.%f是解析时候要使用的格式字符串。见http://docs.python.org/library/datetime.html#strftime-strptime-behavior

import datetime 

times = """ 
09:50:08.650000 
09:50:08.665000 
09:50:08.820000 
09:50:08.877000 
09:50:09.897000 
09:50:09.907000 
09:50:09.953000 
09:50:10.662000 
09:50:10.662000 
""".split() 

# parse all times 
times = [datetime.datetime.strptime(x, "%H:%M:%S.%f") for x in times] 
for i in range(len(times) - 1): 
    # compute timedelta between current and next time in the list 
    print times[i + 1] - times[i] 

结果:

0:00:00.015000 
0:00:00.155000 
0:00:00.057000 
0:00:01.020000 
0:00:00.010000 
0:00:00.046000 
0:00:00.709000 
0:00:00 

要输出以毫秒为单位的区别:

delta = times[i + 1] - times[i] 
print ((delta.days * 24 * 60 * 60 + delta.seconds) * 1000 + delta.microseconds/1000) 

注意timedelta只存储天,秒和毫秒内。其他单位转换。

相关问题