0

I want to compare two timestamps and see if there are in 3 seconds. The first format will be like 13:15:19.654 and the second will be like 1:15:20 PM. How can I implement?

For example:

13:15:19.654 and 1:15:20 PM return True

13:15:19.654 and 1:15:25 PM return False

Note, both timestamps are string from different file. Here is my code:

deviation = 3
timestamp_a = '13:15:19.654'
timestamp_b = '1:15:25 PM'

hour_a = timestamp_a.split(':')[0]
hour_b = timestamp_b.split(':')[0]
if 'PM' in timestamp_b:
  hour_b = str(int(hour_b) + 12)

minute_a = timestamp_a.split(':')[1]
minute_b = timestamp_b.split(':')[1]

second_a = timestamp_a.split(':')[2].split('.')[0]
second_b = timestamp_b.split(':')[2].split()[0]

time_a = int(hour_a) * 3600 + int(minute_a) * 60 + int(second_a)
time_b = int(hour_b) * 3600 + int(minute_b) * 60 + int(second_b)

return abs(time_a - time_b) < deviation
Community
  • 1
  • 1
LaoDa581
  • 563
  • 4
  • 18

2 Answers2

2

You can convert them to datetime and then compute the difference:

from datetime import datetime
timestamp_a = '13:15:19.654'
timestamp_b = '1:15:25 PM'

first_datetime = datetime.strptime(timestamp_a, '%H:%M:%S.%f')
second_datetime = datetime.strptime(timestamp_b, "%I:%M:%S %p")
if abs((first_datetime-second_datetime).total_seconds()) < 3:
  print('Diff less than 3')
  # do something
else:
  print('Diff not less than 3')
  # do something else
Code Pope
  • 5,075
  • 8
  • 26
  • 68
1

Convert string to datetime object and work from there:

import datetime

time_a = datetime.datetime.strptime('13:15:19.654', '%H:%M:%S.%f')
time_b = datetime.datetime.strptime('1:15:20 PM', '%I:%M:%S %p')

delta = time_a - time_b

time_diff = abs(delta.total_seconds())
print('Difference in seconds: ', time_diff)

threshold = 3.0
if time_diff <= threshold:
    print('True')
else:
    print('False')

OUTPUT:

Difference in seconds:  0.346
True

For more datetime format directives check here

Karol Żak
  • 2,158
  • 20
  • 24