Skip to content

Instantly share code, notes, and snippets.

@t00n t00n/trange.py
Created Dec 24, 2017

Embed
What would you like to do?
Small function to iterative over a time range
from datetime import datetime
from time import sleep
def trange(start=None, end=None, interval=1):
now = datetime.now().timestamp()
if start is None:
start = now
else:
start = start.timestamp()
if end is not None:
end = end.timestamp()
if start > now:
sleep(start - now)
now = start
i = 1
while end is None or now < end:
yield datetime.now()
now = datetime.now().timestamp()
target = start + i * interval
if target > now:
sleep(target - now)
now = target
i += 1
if __name__ == '__main__':
from datetime import timedelta
print(datetime.now(), "Starts now, end in 5 seconds, interval 1")
for t in trange(end=datetime.now() + timedelta(seconds=5)):
print(t)
print(datetime.now(), "Starts in 5 seconds, ends in 10 seconds, interval 1")
for t in trange(start=datetime.now() + timedelta(seconds=5), end=datetime.now() + timedelta(seconds=10)):
print(t)
print(datetime.now(), "Starts now, never ends, interval 5")
for t in trange(interval=5):
print(t)
sleep(2) # as long as it's less than the interval it will work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.