Group Python Events into Sessions with a Gap Timeout
Groups timestamped events into sessions, starting a new session when the time gap exceeds a specified timeout.
Python code
44 linesfrom itertools import groupby
from datetime import datetime, timedelta
def session_window_group(events, gap_seconds=300):
"""Group events into sessions where gap > gap_seconds starts a new session."""
if not events:
return []
events = sorted(events, key=lambda x: x[0])
sessions = []
current_session = []
previous_time = None
for timestamp, event in events:
if previous_time is None or (timestamp - previous_time).total_seconds() > gap_seconds:
if current_session:
sessions.append(current_session)
current_session = [event]
else:
current_session.append(event)
previous_time = timestamp
if current_session:
sessions.append(current_session)
return sessions
if __name__ == "__main__":
# Mock events: (timestamp, event_name)
base_time = datetime(2025, 1, 1, 10, 0, 0)
mock_events = [
(base_time, "page_view"),
(base_time + timedelta(seconds=120), "click"),
(base_time + timedelta(seconds=250), "scroll"),
(base_time + timedelta(seconds=310), "click"),
(base_time + timedelta(seconds=600), "page_view"),
(base_time + timedelta(seconds=720), "click"),
(base_time + timedelta(seconds=1500), "page_view"),
]
sessions = session_window_group(mock_events, gap_seconds=300)
for i, session in enumerate(sessions, 1):
print(f"Session {i}: {session}")
Output
Session 1: ['page_view', 'click', 'scroll', 'click']
Session 2: ['page_view', 'click']
Session 3: ['page_view']
How it works
The function sorts events by timestamp first to ensure chronological order, then iterates, starting a new session when the gap between consecutive events exceeds gap_seconds. The condition previous_time is None handles the first event. Each session accumulates events until a gap is detected, then flushes to the results. This simple stateful loop avoids extra libraries and works well for moderate event lists.
Common mistakes
- Forgetting to sort events before grouping, leading to incorrect session boundaries.
- Using >= instead of > for the gap comparison, which splits sessions on exactly the gap timeout.
- Not handling empty input, causing errors or incorrect output.
- Assuming timestamps are already sorted when they may come from logs or APIs.
Variations
- Use pandas with `pd.cut` and time-based windows for larger datasets.
- Use the `more-itertools` package or custom generator for lazy evaluation.
Real-world use cases
- Analytics tools group user clicks and page views into usage sessions for engagement metrics.
- Customer support platforms tag chat messages into sessions using idle timeouts for response tracking.
- Security monitoring groups login attempts into sessions to detect brute-force patterns.
Sponsored
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.