4

我有两次以下格式。我想以毫秒为单位找到时间差。这仅提供秒精度。如何使这项工作持续几毫秒?谢谢。蟒蛇新手。

import time
t1 = "2013-09-13 15:43:35,893"
t2 = "2013-09-13 15:43:45,147"
TIME_FORMAT2 = "%Y-%m-%d %H:%M:%S,%f"
t11 = time.mktime(time.strptime(t1, TIME_FORMAT2))
t12 = time.mktime(time.strptime(t2, TIME_FORMAT2))
print t11-t12
4

2 回答 2

6
>>> from datetime import datetime
>>> datetime.strptime(t1, TIME_FORMAT2) - datetime.strptime(t2, TIME_FORMAT2)
datetime.timedelta(-1, 86390, 746000)
>>> _.total_seconds()
-9.254
于 2013-09-17T02:25:30.343 回答
0

如果您想在同一个对象中使用毫秒和日期,请使用datetime对象。不幸的是,没有您给定格式的日期/时间解析器。不过,您可以使用简单的正则表达式:

import time, datetime, re

dt_pat = re.compile(r"(\d+)\-(\d+)-(\d+)\s+(\d+):(\d+):(\d+),(\d+)")
def mstime( tstr ):
    m = dt_pat.match( tstr )
    if m==None: return m
    v = [int(s) for s in m.groups()]
    return datetime.datetime(*v)


t1 = "2013-09-13 15:43:35,893"
t2 = "2013-09-13 15:43:45,147"
dt1 = mstime( t1 )
dt2 = mstime( t2 )
diff = dt2-dt1
print diff.total_seconds()
于 2013-09-17T02:41:52.917 回答