Python loop to run for certain amount of seconds

后端 未结 6 1402
萌比男神i
萌比男神i 2020-12-02 22:08

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 thro

6条回答
  •  Happy的楠姐
    2020-12-02 22:44

    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.

提交回复
热议问题