4

I have two times in the following format. I want to find the time difference in milliseconds. This is giving only seconds accuracy. How to make this work for milliseconds ? Thanks. New to python.

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 に答える