user2785866
user2785866

Reputation: 41

Difference between 2 given times in milliseconds in python

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

Upvotes: 4

Views: 8414

Answers (2)

Mike Housky
Mike Housky

Reputation: 4069

If you want milliseconds and dates in the same object, use a datetime object. Unfortunately, there's no parser for date/time in the format you're given. You can use a simple regular expression, though:

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

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304137

>>> from datetime import datetime
>>> datetime.strptime(t1, TIME_FORMAT2) - datetime.strptime(t2, TIME_FORMAT2)
datetime.timedelta(-1, 86390, 746000)
>>> _.total_seconds()
-9.254

Upvotes: 6

Related Questions