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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…