TimeDeque is a small Python utility for keeping only the most recent items in a deque.
Each item is stored with the time it was added. When items become older than the configured time window, they are automatically removed.
pip install timedequefrom timedeque import TimeDeque
from time import sleep
dq = TimeDeque(seconds=2)
dq.append("first")
dq.append("second")
print(list(dq))
# ['first', 'second']
sleep(3)
print(list(dq))
# []Python's built-in collections.deque is useful for storing ordered data, but it does not remove items based on age.
TimeDeque is useful when you only care about recent events, such as:
- recent trades
- recent errors
- rate-limit windows
- rolling event buffers
- short-term signals
Creates a new deque that keeps items for the given number of seconds.
dq = TimeDeque(seconds=60)Adds an item to the deque with the current time.
dq.append("event")Returns the number of non-expired items.
len(dq)Returns True if the deque has any non-expired items.
if dq:
print("There are recent items")You can iterate over the current non-expired items.
for item in dq:
print(item)You can access an item by index.
first_item = dq[0]Returns the current non-expired items as a regular list.
items = dq.to_list()Removes all items.
dq.clear()from timedeque import TimeDeque
from time import sleep
errors = TimeDeque(seconds=300)
errors.append("connection failed")
errors.append("timeout")
if len(errors) >= 2:
print("Multiple recent errors")Python 3.10 or newer.
MIT License.