Build a rolling seven-day date range
A rolling date window should be anchored to an explicit reporting date rather than to date.today(). That makes scheduled reports reproducible and makes tests independent of the machine clock. In this example, the input is 2025-03-10, interpreted as the inclusive end of the range. Subtracting six calendar days gives the inclusive start, so the generated list contains exactly seven dates: March 4 through March 10.
datetime.date supports addition and subtraction with timedelta; date arithmetic uses the delta’s whole-day component. timedelta(weeks=1) is seven days, but this task needs an inclusive seven-item list, so range(7) makes the boundary rule visible. The assertions verify both endpoints and the item count for this specific input. They do not prove that the surrounding reporting system has chosen the intended timezone or business-day definition.
Use date values when the requirement is calendar-based. If the anchor begins as an instant, first decide which timezone determines its reporting date; converting an instant to a date too early can put it in the wrong local day. The date arithmetic APIs are available in Python 3.2 and later, while this complete annotated example requires Python 3.9 or later because it uses list[date]. See the official date arithmetic documentation and timedelta documentation.
AI assistance disclosure: This article was drafted with AI assistance and should be reviewed in the context of its application.
from datetime import date, timedelta
def rolling_seven_days(end_date: date) -> list[date]:
start_date = end_date - timedelta(days=6)
return [start_date + timedelta(days=offset) for offset in range(7)]
window = rolling_seven_days(date(2025, 3, 10))
assert len(window) == 7
assert window[0] == date(2025, 3, 4)
assert window[-1] == date(2025, 3, 10)
print(",".join(day.isoformat() for day in window))
2025-03-04,2025-03-05,2025-03-06,2025-03-07,2025-03-08,2025-03-09,2025-03-10
Comments
Post a Comment