10

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

1
  • 4
    now is defined outside while and hence, will be a constant value. Commented Jul 6, 2013 at 10:55

4 Answers 4

8

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
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

1

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

Comments

0

You are storing the current time in now variable. Instead you should get the current time inside the loop everytime:

import datetime
import time

minute = datetime.datetime.now().minute

while minute < 46 :
    print "test"
    time.sleep(5)
    minute = datetime.datetime.now().minute

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.