Python - Working out if time now is between two times
def is_hour_between(start, end, now):
is_between = False
is_between |= start <= now <= end
is_between |= end < start and (start <= now or now <= end)
return is_between
test with:
assert is_hour_between(6, 10, 6)
assert not is_hour_between(6, 10, 4)
assert is_hour_between(17, 20, 17)
assert not is_hour_between(17, 20, 16)
To find out whether a given time (no date) is in between given start, end times (the end is not included):
def in_between(now, start, end):
if start <= end:
return start <= now < end
else: # over midnight e.g., 23:30-04:15
return start <= now or now < end
Example:
from datetime import datetime, time
print("night" if in_between(datetime.now().time(), time(23), time(4)) else "day")
Your code is a bit chaotic. I would do something like this:
import datetime
DAY, NIGHT = 1, 2
def check_time(time_to_check, on_time, off_time):
if on_time > off_time:
if time_to_check > on_time or time_to_check < off_time:
return NIGHT, True
elif on_time < off_time:
if time_to_check > on_time and time_to_check < off_time:
return DAY, True
elif time_to_check == on_time:
return None, True
return None, False
on_time = datetime.time(23,30)
off_time = datetime.time(4,15)
timenow = datetime.datetime.now().time()
current_time = datetime.datetime.now().time()
when, matching = check_time(current_time, on_time, off_time)
if matching:
if when == NIGHT:
print("Night Time detected.")
elif when == DAY:
print("Day Time detected.")