开发者

Print Difference Between Time in Ms

I am reading a log file in my python script, and I have got a list of tuples of startTimes and 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]')

How can I ta开发者_如何学运维ke a difference of the times in milliseconds?


>>> 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

This even works if the clock wraps around at midnight:

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


You can try the datetime package. (http://docs.python.org/library/datetime.html)

First read the time per strftime. (http://docs.python.org/library/datetime.html#strftime-strptime-behavior)

Then substract them, which should give you a timedeltaobject (http://docs.python.org/library/datetime.html#datetime.timedelta) in which you will find your millisecounds.


I thought it would be fun to see if this could be done in a oneliner. And yes, it can (split out for a faint attempt at readability):

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]))

This is Python 2.6. In 2.7 it can be shortened using timedelta.total_seconds(). In Python 3, the reduce() function must be imported from somewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜