Python: timestamp analysis and calculation of time differences in milliseconds

I have a list of timestamps in the format "% H:% M:% S". for instance

09:50:08.650000 09:50:08.665000 09:50:08.820000 09:50:08.877000 09:50:09.897000 09:50:09.907000 09:50:09.953000 09:50:10.662000 09:50:10.662000 

I need to efficiently calculate in python the time difference in milliseconds between each line.

+4
source share
2 answers

%H:%M:%S.%f is a format string that will be used when parsing time. See http://docs.python.org/library/datetime.html#strftime-strptime-behavior

 import datetime times = """ 09:50:08.650000 09:50:08.665000 09:50:08.820000 09:50:08.877000 09:50:09.897000 09:50:09.907000 09:50:09.953000 09:50:10.662000 09:50:10.662000 """.split() # parse all times times = [datetime.datetime.strptime(x, "%H:%M:%S.%f") for x in times] for i in range(len(times) - 1): # compute timedelta between current and next time in the list print times[i + 1] - times[i] 

Result:

 0:00:00.015000 0:00:00.155000 0:00:00.057000 0:00:01.020000 0:00:00.010000 0:00:00.046000 0:00:00.709000 0:00:00 

To output the difference in milliseconds:

 delta = times[i + 1] - times[i] print ((delta.days * 24 * 60 * 60 + delta.seconds) * 1000 + delta.microseconds / 1000) 

Please note that timedelta only stores days, seconds and microseconds. Other units are converted.

+7
source

Have you tried the datetime.strptime() function? It will read in datetime as a string and convert it to a datetime object.

Then you can use datetime.timedelta() to calculate the difference in milliseconds.

Documentation here: http://docs.python.org/library/datetime.html#strftime-strptime-behavior

+2
source

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


All Articles