Session window gap mock in Python
Group sorted timestamps into sessions where any gap between consecutive events exceeds a threshold starts a new session.
Python code
37 linesfrom datetime import datetime, timedelta
def session_windows(timestamps, gap_seconds=300):
"""Group timestamps into sessions where gaps > gap_seconds start new sessions."""
if not timestamps:
return []
# Sort timestamps chronologically to ensure correct windowing
timestamps = sorted(timestamps)
sessions = [[timestamps[0]]]
session_start = timestamps[0]
for ts in timestamps[1:]:
if (ts - session_start).total_seconds() > gap_seconds:
# Start a new session if gap from session start exceeds threshold
sessions.append([ts])
session_start = ts
else:
# Same session, append to current
sessions[-1].append(ts)
return sessions
if __name__ == "__main__":
base = datetime(2025, 1, 1, 10, 0, 0)
mock_timestamps = [
base,
base + timedelta(minutes=2), # same session
base + timedelta(minutes=10), # > 5 min gap → new session
base + timedelta(minutes=11), # same as previous
base + timedelta(hours=1), # > 5 min gap → new session
]
for i, session in enumerate(session_windows(mock_timestamps, gap_seconds=300), 1):
print(f"Session {i}: {[ts.strftime('%H:%M:%S') for ts in session]}")
Output
Session 1: ['10:00:00', '10:02:00']
Session 2: ['10:10:00', '10:11:00']
Session 3: ['11:00:00']
How it works
The function sorts the timestamps first so they are processed in chronological order. It tracks the start of the current session and compares each new timestamp against that start, not the previous event. If the gap from session start exceeds the threshold, a new session begins and the session start resets. Otherwise, the timestamp belongs to the current session and is appended. This mimics typical session windowing behavior used in analytics.
Common mistakes
- Comparing each event to the previous one instead of the session start, which splits sessions incorrectly.
- Forgetting to sort timestamps, leading to non-chronological sessions.
- Using a gap threshold in minutes but comparing seconds without conversion.
- Returning lists of timestamps without formatting or handling empty input.
Variations
- Use a for loop with an explicit index and compare against session_start, updating only on new sessions.
- Implement with `groupby` from itertools, but this requires precomputing session IDs.
Real-world use cases
- Grouping web analytics clickstream events into user sessions for funnel analysis.
- Segmenting server logs into distinct job runs based on idle time gaps.
- Bucketting sensor readings into active periods for anomaly detection.
Sponsored
More from Big data & Spark
Keep learning
Related tutorials and quizzes for this topic.