-1

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!

questionmark
  • 335
  • 1
  • 13
  • Does this answer your question:https://stackoverflow.com/questions/8419564/difference-between-two-dates-in-python? – Dani Mesejo Nov 01 '21 at 00:47
  • Also, for parsing your strings into datetime objects see https://stackoverflow.com/a/698279/13113537 – Luiz Nov 01 '21 at 00:50
  • Can use *datetime.strptime()* to parse time strings then substract one datetime from the other for the time delta and call total_seconds() for float of values in seconds. – CodeMonkey Nov 02 '21 at 21:38

2 Answers2

0

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.

Tyler Liu
  • 989
  • 1
  • 6
  • 7
0

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
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75