brandon evans brandon evans - 3 months ago 9
Python Question

now_time is not getting updated while code is looping

i'm trying to do a loop, that keeps checking if time is between 2 times.. so it turns my lights on. but while its looping the current time does not get updated. im trying to create a aquarium controller, that turns 3 sets of lights on a different times.

thanks for your help :)

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
SleepTimeL = 2

if now_time >= time (9,30) and now_time <= time (16,15):
print "yes, within the interval"
print now_time
time.sleep( 9 )

else:
print "no"

Answer

You'll need to keep updating now_time in your loop:

while True:
    if time (9,30) <= now_time <= time (16,15):
        print "yes, within the interval"
        now_time = datetime.now().time()
        print now_time
        time.sleep( 9 )
    else:
        print "no"

You can replace the conditions with a chained comparison, which is more readable.

You can also set the comparison as the condition on the while, in which case the loop only runs in the specified duration and needs to be restarted for the cycle of the duration:

while time (9,30) <= now_time <= time (16,15):
    print "yes, within the interval"
    now_time = datetime.now().time()
    print now_time
    time.sleep( 9 )