Difference between two given times in milliseconds in python

I have two times in the following format. I want to find the time difference in milliseconds. This gives only second accuracy. How to make this work in milliseconds? Thank you New for 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
source share
2 answers
 >>> from datetime import datetime >>> datetime.strptime(t1, TIME_FORMAT2) - datetime.strptime(t2, TIME_FORMAT2) datetime.timedelta(-1, 86390, 746000) >>> _.total_seconds() -9.254 
+6
source

If you need milliseconds and dates in one object, use the datetime object. Unfortunately, there is no date and time analyzer in the format you give. You can use a simple regular expression:

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

Source: https://habr.com/ru/post/1502527/


All Articles