5

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.

Luciano
  • 367
  • 7
  • 17

3 Answers3

3

Compare the timedelta difference to two other timedeltas:

from datetime import timedelta
if timedelta(minutes=-30) <= difference <= timedelta(minutes=120):
deceze
  • 491,798
  • 79
  • 706
  • 853
0

You can, I think, build upon the accepted answer at Time difference in seconds from numpy.timedelta64.

>>> import numpy as np
>>> a = np.datetime64('2012-05-01T01:00:00.000000+0000')
>>> b = np.datetime64('2012-05-15T01:00:00.000000+0000')
>>> diff=b-a
>>> diff.item().total_seconds()
1209600.0
>>> minutes = 1209600.0/60
>>> minutes
20160.0
>>> -30 <= minutes <= 120
False
Community
  • 1
  • 1
Bill Bell
  • 20,186
  • 5
  • 41
  • 55
0

You could also convert all values to seconds, and then compare those values:

difference_in_seconds = difference.total_seconds()
thirty_minutes_in_seconds = 1800
one_hundred_and_twenty_minutes_in_seconds = 7200

if thirty_minutes_in_seconds <= difference_in_seconds <= one_hundred_and_twenty_minutes_in_seconds: 
    # Do stuff
CodeBiker
  • 2,417
  • 2
  • 30
  • 34