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
  • 426
  • 2
  • 9
  • 19

3 Answers3

4

Compare the timedelta difference to two other timedeltas:

from datetime import timedelta
if timedelta(minutes=-30) <= difference <= timedelta(minutes=120):
deceze
  • 510,633
  • 85
  • 743
  • 889
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
  • 21,021
  • 5
  • 43
  • 58
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,985
  • 2
  • 33
  • 36