Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two datetimes are within a certain range of each other?

I have two datetime64 objects, a and b, and I want to determine if they are within a certain range of each other. However, the range is not symmetrical. If a is within -30 and 120 minutes of b (a is between half an hour earlier and two hours later than b), the two are within the desired range. My datetime objects look like %m/%d/%Y %H:%M. I tried saying:

difference = a - b
if (-30 <= difference <= 120):
    #Do stuff

However, this doesn't work because difference is not in minutes. I am not sure how to perform this comparison. I know timedelta can be used for datetime comparisons, but I don't know how to use it with an asymmetric range like this one.

Thanks.

like image 745
Luciano Avatar asked Oct 17 '22 16:10

Luciano


1 Answers

Compare the timedelta difference to two other timedeltas:

from datetime import timedelta
if timedelta(minutes=-30) <= difference <= timedelta(minutes=120):
like image 145
deceze Avatar answered Oct 21 '22 02:10

deceze