Finger twist
Finger twist

Reputation: 3786

executing a while loop between defined time

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

Upvotes: 10

Views: 8095

Answers (4)

Bleeding Fingers
Bleeding Fingers

Reputation: 7129

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

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121316

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.

Upvotes: 5

pkacprzak
pkacprzak

Reputation: 5629

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

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

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

Upvotes: 8

Related Questions