Home > Mobile >  Python: Arithmetic operations with miliseconds in string format
Python: Arithmetic operations with miliseconds in string format

Time:11-01

I have time variables that are currently strings:

Time
18:29:36.809889
18:30:16.291965  

I want to compute the difference between those two values (perhaps as a floating point). How do I parse the string and perform the operation?

Thanks!

CodePudding user response:

This code will produce the difference in seconds

time1 = "18:29:36.809889"
time2 = "18:30:16.291965"
hr1, min1, sec1  = time1.split(":")
hr2, min2, sec2 = time2.split(":")
ms1 = float(sec1)   int(min1)*60   int(hr1)*60*60
ms2 = float(sec2)   int(min2)*60   int(hr2)*60*60
print(abs(ms2 - ms1))

I must add however, that computing time differences using string manipulation is not the right approach. Wherever you're getting the timestamps from, you could convert them to epoch time and get the difference much easier.

CodePudding user response:

Convert time strings to datetime instances then take the difference which is a timedelta object from which you can get a floating-point value as the total number of seconds.

from datetime import datetime
a = '18:29:36.809889'
b = '18:30:16.291965'
date1 = datetime.strptime(a, '%H:%M:%S.%f')
date2 = datetime.strptime(b, '%H:%M:%S.%f')
delta = date2 - date1
print(delta)
print(delta.total_seconds(), "seconds")

Output:

0:00:39.482076
39.482076 seconds
  • Related