pythontimetimerwhile-loop

Python loop to run for certain amount of seconds


I have a while loop, and I want it to keep running through for 15 minutes. it is currently:

while True:
    #blah blah blah

(this runs through, and then restarts. I need it to continue doing this except after 15 minutes it exits the loop)

Thanks!


Solution

  • Try this:

    import time
    
    t_end = time.time() + 60 * 15
    while time.time() < t_end:
        # do whatever you do
    

    This will run for 15 min x 60 s = 900 seconds.

    Function time.time returns the current time in seconds since 1st Jan 1970. The value is in floating point, so you can even use it with sub-second precision. In the beginning the value t_end is calculated to be "now" + 15 minutes. The loop will run until the current time exceeds this preset ending time.