S
S
s1vemod2021-08-06 20:17:50
Python
s1vemod, 2021-08-06 20:17:50

How to correctly calculate the time difference?

Good afternoon, I wrote the following function:

def check_difference_time(start, end):
  FMT = '%H:%M'
  tdelta = datetime.strptime(end, FMT) - datetime.strptime(start, FMT)
  return tdelta >= timedelta(hours=1, minutes=30)


Where, start and end are two times. For example - "13:00" and "14:30"
This function checks if there are 1.5 hours between them.

But if I pass "22:00" and "01:30" it returns False, if you look at tdelta it is:
-1 day, 3:00:00

I guess the problem is -1 day, how can I do this avoid and beautifully solve this problem?

This code checks if there is a difference of one and a half hours, but we must also take into account that:
"23:30" and "00:30" -> False. Yes, the day is different, but there is no difference in an hour and a half.
"23:00" and "00:30" -> True.

Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom, 2021-08-06
@s1vemod

I don't know about beautiful, but here's what I managed to achieve

from datetime import datetime

FMT = '%H:%M'
print((datetime.strptime("01:30", FMT) - datetime.strptime("22:00", FMT)).seconds)  # => 12600 - это правильно

Can be compared with seconds in the same way

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question