Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Check if a Minute has passed

Tags:

python

Im running part of a script just once per minute and came up with this:

def minutePassed(oldminute):
    currentminute = time.gmtime()[4]

    if ((currentminute - oldminute) >= 1) or (oldminute == 59 and currentminute >= 0):
        return True
    else:
        return False

Problem here is that if the minute is 59 it runs everytime until its past that time - its not much of a bother performance wise for me. But I still dont like it happening!

I thought of something like this now:

def minutePassed(oldminute):
    currentminute = time.gmtime()[4]

    if ((currentminute - oldminute) >= 1) or (oldminute == 59 and currentminute >= 0 and ran == false):
        ran = True
        return True
    else:
        return False

Then on another part of the script I turn ran false again when the minute is != 59 and the variable isnt already false - but that seems crude?

On another note - is there any other way to check if a minute has passed? Maybe im making things complicated ...

Edit: Maybe I was not clear enough:

  1. Run only ONCE per minute.
  2. Execution time varies by many seconds but takes less then 30s.

Im looking at timedelta now.

like image 658
Jrc Avatar asked Apr 14 '13 14:04

Jrc


People also ask

How do I check if a specific time has passed Python?

To measure time elapsed during program's execution, either use time. clock() or time. time() functions. The python docs state that this function should be used for benchmarking purposes.

How do you check if time is greater than or less than a specific time in python?

now(). time() print(time_in_range(start, end, current)) # True (if you're not a night owl) ;) The code returns True if you run it between (hh:mm:ss) 00:00:00 and 23:55:00 on your computer. Only if you run it between 23:55:00 and 23:59:59 it returns False .

How do you add elapsed time in python?

Use time. time() and subtraction to measure time elapsed time() after the start time. Subtract the start point from the end point to get time elapsed in seconds.


1 Answers

Don't work with minutes like that; if the time is, for example, 00:00:59, your code will believe a minute has passed the very next second.

Instead, use something like time.time(), which returns seconds passed since the epoch:

def minute_passed(oldepoch):
    return time.time() - oldepoch >= 60

That can still be off by almost a second for the same reasons, but that's probably more acceptable.

like image 74
Cairnarvon Avatar answered Oct 17 '22 08:10

Cairnarvon