How do I determine if current time is within a specified range using Python's datetime module?
My original answer focused very specifically on the question as posed and didn't accommodate time ranges that span midnight. As this is still the accepted answer 6 years later, I've incorporated @rouble's answer below that expanded on mine to support midnight.
from datetime import datetime, time
def is_time_between(begin_time, end_time, check_time=None):
# If check time is not given, default to current UTC time
check_time = check_time or datetime.utcnow().time()
if begin_time < end_time:
return check_time >= begin_time and check_time <= end_time
else: # crosses midnight
return check_time >= begin_time or check_time <= end_time
# Original test case from OP
is_time_between(time(10,30), time(16,30))
# Test case when range crosses midnight
is_time_between(time(22,0), time(4,00))
I still stick to my original comment below that most applications of this logic would probably be better suited with datetime
objects where crossing midnight is reflected as a date change anyway.
The above accepted solution does not work with overnight times, this does:
import datetime as dt
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else:
#Over midnight:
return nowTime >= startTime or nowTime <= endTime
#normal example:
isNowInTimePeriod(dt.time(13,45), dt.time(21,30), dt.datetime.now().time())
#over midnight example:
isNowInTimePeriod(dt.time(20,30), dt.time(1,30), dt.datetime.now().time()))
here's little example for @rouble's answer:
from datetime import datetime
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else: #Over midnight
return nowTime >= startTime or nowTime <= endTime
timeStart = '3:00PM'
timeEnd = '11:00AM'
timeNow = '2:59AM'
timeEnd = datetime.strptime(timeEnd, "%I:%M%p")
timeStart = datetime.strptime(timeStart, "%I:%M%p")
timeNow = datetime.strptime(timeNow, "%I:%M%p")
print(isNowInTimePeriod(timeStart, timeEnd, timeNow))