Start learning free

LESSON 68 OF 107 · DATA ENGINEERING: STREAMING BASICS

Counts per Minute: Windows in Python

Practice

The running total of the first lesson grows forever and can't tell you when the shop was busy. A dashboard wants orders and revenue per minute. A tumbling window cuts time into blocks of the same size that never overlap: 10:00 to 10:01, 10:01 to 10:02, and so on. Each event lands in exactly one window, picked by its event_time, the moment it happened. Without windows, a data engineer can't say when a rush started, or raise an alert when orders stop coming.

Cutting a time to its window: every event_time is written the same way, like "2026-05-01 10:00:40", so a slice of the string gives its window. [:16] keeps the first 16 characters: the date, the hour and the minute. The date stays in, so 10:00 on another day is another window. For one-hour windows you would keep 13 characters:

print("2026-05-01 14:37:12"[:13])   # 2026-05-01 14

One total per window: keep a dict keyed by window. A plain dict raises KeyError when you read a key it doesn't have yet. A defaultdict(int), from collections (the starting code already imports it), gives 0 for a missing key, so the first event of a minute needs no check:

views = defaultdict(int)
views["home"] = views["home"] + 1
print(views["home"], views["faq"])   # 1 0

The starting code holds 11 order events and a loop that prints each window of orders, in time order. Your code must make it print:

2026-05-01 10:00 | orders: 3 | revenue: 105
2026-05-01 10:01 | orders: 1 | revenue: 12
2026-05-01 10:02 | orders: 3 | revenue: 125
2026-05-01 10:04 | orders: 3 | revenue: 46
2026-05-01 10:05 | orders: 1 | revenue: 29
2026-05-01 10:03 (no events) | orders: 0 | revenue: 0

No event happened in 10:03, so it never becomes a key and the loop skips it; the last line comes from the check, which asks for 10:03 by name and gets 0. Stream tools that read from Kafka, such as Kafka Streams or Flink, give you tumbling windows built in and save each window's counts as they go, so a restart doesn't lose them.

Your task: below events, make orders and revenue, each a defaultdict(int). Loop over the events, cut each event_time to its minute with [:16], then add 1 to that window's orders and the event's amount to its revenue.


Assignment
Follow the Coding Tutorial to count orders and revenue per one-minute window.


Hint
Both dicts use the same key, window. With defaultdict(int), orders[window] + 1 works even for the first event of a minute.


STEP 1 OF 5
    Ctrl + Enter to check

    De Stream Windows in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free