Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executing a while loop between defined time

Tags:

python

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

like image 641
Finger twist Avatar asked Jul 06 '13 10:07

Finger twist


People also ask

How do you make something loop at a certain amount of time in Python?

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.

How do you break a loop after some time Python?

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.


3 Answers

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
like image 60
Ashwini Chaudhary Avatar answered Oct 08 '22 07:10

Ashwini Chaudhary


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.

like image 33
Martijn Pieters Avatar answered Oct 08 '22 06:10

Martijn Pieters


The loop's proposition should be datetime.datetime.now().minute - minute < 46 and the body of the loop shouldn't be updating minute.

like image 29
Bleeding Fingers Avatar answered Oct 08 '22 05:10

Bleeding Fingers