Check if time is between tonight and tomorrow morning

Viewed 9960

The following condition does not work, any idea? Does Python think that 8am belongs to the same day and so this condition is not possible?

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time >= time(23,00) and now_time <= time(8,00): 
    try:
        print 'hall light turning on'
    except:
        print 'Could not connect to Hue gateway'
5 Answers

you could simplify it to this

if time(8, 00) <= now_time >= time(18, 00):

the full code below

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if time(8, 00) <= now_time >= time(18, 00):
    try:
        print("hall light turning on")
    except:
        print("Could not connect to Hue gateway")
Related