Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time based for loop in Python

I have a program which includes execution of time based while loop. Some thing like..

import time
endtime=time.time()+60.0 #1minute
while (time.time()<endtime):
    do something

I was just wondering if this is possible using for loop? Can I build a time based for loop in python?

like image 505
Bhoomika Sheth Avatar asked Oct 28 '25 08:10

Bhoomika Sheth


1 Answers

Sure. Here's an iterator that gives you the time since start over and over until it reaches the end:

def time_counter(seconds):
    starttime = time.time()
    while True:
        now = time.time()
        if now > starttime + seconds:
            break
        yield now - starttime

for t in time_counter(20):
    print(t)
    time.sleep(3)

When I run this, it outputs:

9.5367431640625e-07
3.002220869064331
6.0040669441223145
9.004395961761475
12.006848812103271
15.009617805480957
18.011652946472168

If you need some different value, just change the yield expression.

If you don't need any value… then you don't need a for statement; your existing code is already perfectly readable, and a for loop that iterates over and discards some meaningless values is just going to make it confusing.

like image 107
abarnert Avatar answered Oct 31 '25 10:10

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!