Slice Sorted Python Events by Time with bisect_left

A build timeline has several events at the same elapsed millisecond. A report for the window from 100 to 200 ms should include every event at 100 ms and leave events at 200 ms for the next window. If the timeline is already sorted, two calls to bisect_left() find the slice without scanning all the events for each report.

Find the First Index at Each Boundary

Start with a sorted list of elapsed milliseconds.

1
2
3
4
5
6
7
8
from bisect import bisect_left

times_ms = [80, 100, 100, 150, 200, 200, 250]
first = bisect_left(times_ms, 100)
stop = bisect_left(times_ms, 200)

print(first, stop)            # 1 4
print(times_ms[first:stop])   # [100, 100, 150]

bisect_left() finds the first position whose value is at least the target. For 100 it returns the index of the first 100, so the slice includes both copies. For 200 it returns the index of the first 200. Because a Python slice excludes its stop index, both copies of 200 stay outside the result. A boundary between timestamps works the same way. The returned index points to the first later timestamp, or to the end of the list if all values are smaller. Python bisect documentation

Search Records by Their Timestamp

With Python 3.10 or later, use key to search records directly. Save this helper as event_window.py. It expects a list of (elapsed_ms, event_name) tuples sorted by the first field, with integer boundaries in the same units.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from bisect import bisect_left
from operator import itemgetter

elapsed_ms = itemgetter(0)


def events_in_window(events, start_ms, end_ms):
    if end_ms < start_ms:
        raise ValueError("end_ms must be greater than or equal to start_ms")

    first = bisect_left(events, start_ms, key=elapsed_ms)
    stop = bisect_left(events, end_ms, key=elapsed_ms)
    return events[first:stop]

The key function runs on records during the search. It does not run on the boundary arguments, so pass 100 directly as the start value. The helper returns a new list and preserves the order of records with equal timestamps.

Put Shared Boundaries in the Next Window

Save this as show_windows.py beside the helper and run python show_windows.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from event_window import events_in_window

events = [
    (80, "queued"),
    (100, "opened"),
    (100, "read config"),
    (150, "compiled"),
    (200, "linked"),
    (200, "wrote output"),
    (250, "closed"),
]

print(events_in_window(events, 100, 200))
# [(100, 'opened'), (100, 'read config'), (150, 'compiled')]
print(events_in_window(events, 200, 300))
# [(200, 'linked'), (200, 'wrote output'), (250, 'closed')]

These windows use the rule start_ms <= elapsed_ms < end_ms. The 200 ms events belong to the second window only. Replacing the stop search with bisect_right() would also include them in the first window. Equal start and end values give an empty slice because both searches return the same index.

Keep the Input Sorted Between Queries

Sort incoming records once by elapsed time if they can arrive out of order. Python’s sort preserves the input order of records that share the same sort key. Keep the list stable during a query so the searches and slice see the same data. If you append records later, keep timestamps in nondecreasing order or sort again before querying.

Each search takes logarithmic time on the sorted list. Returning the slice takes time and additional list storage proportional to the number of matching records. When the report only needs a count, the difference stop - first already gives it. For a stream that you read once, filtering each record as it arrives avoids building a list to search.

Test Windows Against a Direct Filter

Save this as test_event_window.py beside the helper and run python test_event_window.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from event_window import events_in_window

events = [(100, "a"), (100, "b"), (150, "c"), (200, "d"), (200, "e")]
assert events_in_window([], 100, 200) == []

boundaries = [0, 100, 120, 150, 175, 200, 300]
for start in boundaries:
    for end in boundaries:
        if start <= end:
            expected = [event for event in events if start <= event[0] < end]
            assert events_in_window(events, start, end) == expected

try:
    events_in_window(events, 200, 100)
except ValueError:
    pass
else:
    raise AssertionError("reversed boundaries should raise ValueError")

print("Event window checks passed.")

The filter states the window rule directly and serves as a reference for the slice. The boundary pairs cover duplicates, gaps between timestamps, empty windows, and windows that extend beyond the recorded events.