2011-02-11 133 views
2

我讀我的python腳本中的日誌文件,我有和startTimes元組的列表endTimes -打印差異女士

('[19:49:40:680]', '[19:49:49:128]') 
('[11:29:10:837]', '[11:29:15:698]') 
('[11:30:18:291]', '[11:30:21:025]') 
('[11:37:44:293]', '[11:38:02:008]') 
('[11:39:14:897]', '[11:39:21:572]') 
('[11:42:19:968]', '[11:42:22:036]') 
('[11:43:18:887]', '[11:43:19:633]') 
('[11:44:26:533]', '[11:49:29:274]') 
('[11:55:03:974]', '[11:55:06:372]') 
('[11:56:14:096]', '[11:56:14:493]') 
('[11:57:08:372]', '[11:57:08:767]') 
('[11:59:26:201]', '[11:59:27:438]') 

我如何可以採取一個時代的差異毫秒?

回答

7
>>> import datetime 
>>> a = ('[19:49:40:680]', '[19:49:49:128]') 
>>> start = datetime.datetime.strptime(a[0][:-1]+"000", "[%H:%M:%S:%f") 
>>> end = datetime.datetime.strptime(a[1][:-1]+"000", "[%H:%M:%S:%f") 
>>> delta = end-start 
>>> ms = delta.seconds*1000 + delta.microseconds/1000 
>>> ms 
8448.0 

這甚至工作,如果時鐘在午夜環繞:

>>> a = ('[23:59:59:000]','[00:00:01:000]') 
>>> # <snip> see above 
>>> ms = delta.seconds*1000 + delta.microseconds/1000 
>>> ms 
2000.0 
3

您可以嘗試使用datetime軟件包。 (http://docs.python.org/library/datetime.html)

首先讀取每個strftime的時間。 (http://docs.python.org/library/datetime.html#strftime-strptime-behavior)

然後減去它們,它應該給你一個timedeltaobject(http://docs.python.org/library/ datetime.html#datetime.timedelta),您可以在其中找到毫秒。

3

我認爲這將是有趣的,看看這可以在一個oneliner來完成。是的,它可以(在可讀性方面略微嘗試):

interval = ('[19:49:40:680]', '[19:49:49:128]') 
import datetime 
(lambda td: 
     (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6)/10**3)\ 
    (reduce(
     lambda a, b: b - a, 
     [datetime.datetime.strptime(t[1:-1] + '000', '%H:%M:%S:%f') 
     for t in interval])) 

這是Python 2.6。在2.7中可以使用timedelta.total_seconds()縮短。在Python 3中,reduce()函數必須從某處導入。

+0

+1哇,太好了!但是你能解釋我爲什麼使用td.days,因爲原始日期不包含有關當天的信息嗎? – 2011-02-11 10:05:21