Check if a Timestamp Falls in a Daily Maintenance Window in Python
A small Python function that returns True when a datetime falls inside a daily maintenance window, and a demo printing yes/no for sample timestamps.
Python code
22 linesfrom datetime import datetime, timedelta
from zoneinfo import ZoneInfo
def in_maintenance_window(now: datetime, start_hour: int = 2, duration_hours: int = 4) -> bool:
"""Return True if 'now' falls inside the daily maintenance window."""
day_start = now.replace(hour=start_hour, minute=0, second=0, microsecond=0)
window_end = day_start + timedelta(hours=duration_hours)
return day_start <= now < window_end
if __name__ == "__main__":
fmt = "%Y-%m-%d %H:%M"
tests = [
datetime.fromisoformat("2025-07-10T01:30:00"),
datetime.fromisoformat("2025-07-10T02:30:00"),
datetime.fromisoformat("2025-07-10T05:59:00"),
datetime.fromisoformat("2025-07-10T06:00:00"),
]
for ts in tests:
print(f"{ts.strftime(fmt)} -> maintenance={'yes' if in_maintenance_window(ts) else 'no'}")
Output
2025-07-10 01:30 -> maintenance=no
2025-07-10 02:30 -> maintenance=yes
2025-07-10 05:59 -> maintenance=yes
2025-07-10 06:00 -> maintenance=no
How it works
The in_maintenance_window function builds a naive datetime for the start of the window on the same day as now by calling replace(hour=start_hour, ...). The end is calculated by adding a timedelta, and membership is tested with day_start <= now < window_end, which correctly excludes the exact end time. All values stay naive, so the comparison works directly on local system time; for production you would pass timezone-aware datetimes instead. The demo prints the result for four timestamps around the window boundaries to show inclusive start and exclusive end behavior.
Common mistakes
- Using `<= window_end` instead of `< window_end`, which includes the exact end time.
- Forgetting to reset minutes/seconds/microseconds, leading to an off-by-a-few-seconds window.
- Handling naive datetimes in mixed timezone contexts without first converting to a single timezone.
Variations
- Return the start and end datetimes as a tuple instead of a boolean.
- Support overlapping midnight windows by adding a day when the end hour is less than the start hour.
Real-world use cases
- Gate automated deploys or batch jobs so they don't run during a planned database maintenance window.
- Suppress paging alerts for known maintenance periods to reduce alert fatigue.
- Decide when to run expensive cleanup in a scheduler based on the current wall-clock time.
Sponsored
More from Observability & SRE
- Adding a Correlation ID to Log Context in Python medium
- Calculate Error Rate from Log Stream in Python easy
- Export Metrics with OTLP Mock in Python medium
- Generate Mock CPU and Memory Metrics in Python easy
- Generate Prometheus Text Exposition Format in Python easy
- Generate Synthetic CPU Utilization Metrics in Python easy
Keep learning
Related tutorials and quizzes for this topic.