I'm trying to execute a while loop only under a defined time like this, but the while loop continues its execution even when we are above the defined limit :
import datetime
import time
now = datetime.datetime.now()
minute = now.minute
while minute < 46 :
print "test"
time.sleep(5)
minute = now.minute
How can stop the loop once we cross the limit ?
Thanks
To loop through a set of code a certain number of times, you can use the range() function, which returns a list of numbers starting from 0 to the specified end number.
Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.
You're not updating the value of minute
inside while loop properly. You should recalculate the value of now
in loop and then assign the new now.minute
to minute
.
while minute < 46 :
print "test"
time.sleep(5)
now = datetime.datetime.now()
minute = now.minute
You need to determine the time anew in your loop. The minute
variable is static, it does not update to reflect changing time.
If you want to loop for a certain amount of time, start with time.time()
instead and then calculate elapsed time:
import time
start = time.time()
while time.time() - start < 300:
print 'test'
time.sleep(5)
will print 'test' every 5 seconds for 5 minutes (300 seconds).
You can do the same with datetime
objects of course, but the time.time()
call is a little simpler to work with.
To loop until a certain time datetime
can be used like:
import datetime
while datetime.datetime.now().minute < 46:
print 'test'
time.sleep(5)
Again, note that the loop needs to call a method each time to determine what the current time is.
The loop's proposition should be datetime.datetime.now().minute - minute < 46
and the body of the loop shouldn't be updating minute
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With