tensingd1
tensingd1

Reputation: 11

Python time duration comparison

I am trying to compare two times within accuracy of a second, but i find some times the code calculates differently and my comparison does not work and the loop executes infinitely. I have pasted my code below, for reference

start_time = datetimenow() #datetimenow is a function which returns time w/o microseconds             
end_time =  start_time + timedelta(seconds = GrabDuration)
while datetimenow() != end_time: #this part fails sometimes and passes sometimes
    time.sleep(Grabtime)
    saveas(imggrab())

If you have any other better way of comparing time and time duration i would appreciate it if you could share. GrabDuration & Grabtime is a user given variable for duration.

Upvotes: 0

Views: 1894

Answers (2)

farzad
farzad

Reputation: 8855

I'm assuming datetimenow is returning a standard datetime.datetime object, so basically it's like this:

from datetime import datetime

def datetimenow():
    return datetime.now()

Comparing datetime objects with == or != makes it a bit tricky, because it takes a slight amount of time for them not be equal.

As a test just try these lines in a Python REPL (assuming the lines above are entered as well, so the datetimenow() function is available to call:

datetimenow() == datetimenow()

And it's quite possible among multiple tries, you'll get a few False results.

I'd suggest to compare the datetime objects with safer comparison operators, something like this:

while datetimenow() <= end_time:
    time.sleep(Grabtime)
    saveas(imggrab())

Upvotes: 1

Anuj Bhasin
Anuj Bhasin

Reputation: 610

import datetime
import time
start_time = datetime.datetime.now()
end_time = start_time + datetime.timedelta(seconds = GrabDuration)
while start_time != end_time:
    time.sleep(Grabtime)

if you have comparison between start time and end time, then this while loop of the code will execute infinite times only if start_time not equal to end_time

However the code you have shared, in that the while loop you are again taking the current system time and not using the strat_time variable for your comparison. Please check that.

You can also use datetime.datetime.now().time() method also like datetime.datetime.now().time() < datetime.time(hour=2, minute=10, second=10). This may help you to solve your concerns.

Upvotes: 0

Related Questions