How do I check if a given datetime object is "between" two datetimes?
Asked Answered
S

5

15
my_event = Event.objects.get(id=4)
current_time = datetime.datetime.now()

How do I do check if my current time is between them?

my_event.start_time < current_time < my_event.end_time
Sabinasabine answered 14/4, 2010 at 0:26 Comment(0)
M
11

Your answer is the way to go as long as start_time and end_time don't have an associated tzinfo class. You can't directly compare a naive datetime with a timezoned-datetime.

Montes answered 14/4, 2010 at 0:33 Comment(0)
W
12

you can use a simple if comparing three dates, like this

if date1 < yourdate < date2:
  ...do something...
else:
  ...do ...
Wilkey answered 14/4, 2010 at 5:4 Comment(0)
M
11

Your answer is the way to go as long as start_time and end_time don't have an associated tzinfo class. You can't directly compare a naive datetime with a timezoned-datetime.

Montes answered 14/4, 2010 at 0:33 Comment(0)
D
3

I know old, but since this is so high on Google results, answers here don't take into consideration two cases:

  1. If your time equals either of your range, ie your range is 6-8 and it is 6.
  2. If your time range is say 18:00 to 6:00, valid range; however 19:00 would not match.

I wrote a function to take care of time comparison, hope this helps anyone viewing this old question.

def process_time(intime, start, end):
    if start <= intime <= end:
        return True
    elif start > end:
        end_day = time(hour=23, minute=59, second=59, microsecond=999999)
        if start <= intime <= end_day:
            return True
        elif intime <= end:
            return True
    return False
Deterioration answered 11/5, 2015 at 16:8 Comment(0)
F
0

The datetimes getting tested need to all naive (no timezone) or all aware (timezone). An exception should occur if you try to compare aware and naive. If all the datetimes are aware the timezones don't actually have to match that appears to be taken into consideration when comparing.

e.g.

class RND(datetime.tzinfo):
    """ Random timezone UTC -3 """

    def utcoffset(self, dt):
        return datetime.timedelta(hours=-3)

    def tzname(self, dt):
        return "RND"

    def dst(self, dt):
        return datetime.timedelta(hours=0)


april_fools = datetime.datetime(year=2017, month=4, day=1, hour=12, tzinfo=pytz.UTC)

random_dt = datetime.datetime(year=2017, month=4, day=1, hour=9, tzinfo=RND())

random_dt == april_fools
# True as the same time when converted back to utc.

# Between test of 3 naive datetimes
start_spring = datetime.datetime(year=2018, month=3, day=20)
end_spring = datetime.datetime(year=2018, month=6, day=21)
april_fools = datetime.datetime(year=2018, month=4, day=1)


if start_spring < april_fools < end_spring:
    print "April fools is in spring"
Flessel answered 23/11, 2017 at 4:53 Comment(0)
S
0

This is my script of checking the time between two different timeslots. One for morning and one for evening. This is the extended script using @Clifford's script

def Strategy_Entry_Time_Check():
    current_time = datetime.datetime.now()
    #current_time = current_time.replace(hour=13, minute=29, second=00, microsecond=00) #For testing, edit the time
    morning_start = current_time.replace(hour=9, minute=30, second=00, microsecond=00)
    morning_end = current_time.replace(hour=11, minute=00, second=00, microsecond=00)
    evening_start = current_time.replace(hour=13, minute=00, second=00, microsecond=00)
    evening_end = current_time.replace(hour=15, minute=00, second=00, microsecond=00)
    
    if morning_start <= current_time <= morning_end:
        print("Morning Entry")
        return True
    elif evening_start <= current_time <= evening_end:
        print("Evening Entry")
        return True
    print("No Entry")
    return False
Stratification answered 18/6, 2021 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.