Add business days while skipping weekends
“Three business days after Friday” is not three calendar days after Friday. This example defines business days as Monday through Friday, advances one timedelta(days=1) at a time, and decrements the remaining count only when date.weekday() is below 5. Starting on Friday 2026-05-01, it visits Saturday and Sunday without counting them, then counts Monday, Tuesday, and Wednesday. The returned date is 2026-05-06.
The function deliberately accepts only non-negative counts. Its zero case returns the starting date because the loop does not run. That choice should be stated in a caller’s contract: some systems instead define “zero business days” as the next business day when the input is a weekend. The assertions show the selected convention for this one Friday input and do not prove correctness for every calendar.
Weekends are not a complete business calendar. This code neither knows public holidays nor short working days, regional weekends, closures, or deadlines with times of day. Add those rules from a maintained, jurisdiction-specific source if they matter. The example uses only date, timedelta, and date.weekday() from Python’s standard library and works on Python 3.2+.
The Python datetime documentation defines date arithmetic and documents that weekday() maps Monday to 0 and Sunday to 6.
AI-assistance disclosure: This article was drafted with AI assistance and should be reviewed in its application context.
from datetime import date, timedelta
def add_business_days(start, count):
if count < 0:
raise ValueError("count must be non-negative")
current = start
remaining = count
while remaining:
current += timedelta(days=1)
if current.weekday() < 5:
remaining -= 1
return current
arrival = add_business_days(date(2026, 5, 1), 3)
assert arrival == date(2026, 5, 6)
assert arrival.weekday() == 2
print(arrival.isoformat())
2026-05-06
Comments
Post a Comment