Recipe 15.4 · Python
Business-Day Calculations
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Due dates, SLAs, settlement dates and "respond within five business days" all need date arithmetic that skips weekends and holidays. The typical version loops with DateTime, ignores holidays or reads them from a table on every call, and has an off-by-one error at the edges that only shows up on a Friday.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Add business days by skipping weekends only
Source: ImproveCode, Chapter 15, Recipe 15.4 "Business-Day Calculations"
Section: The way it's often written
Book page: 334-335 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
DateTime becomes datetime (time component kept); weekday() 5/6 are Saturday/Sunday.
"""
from datetime import datetime, timedelta
# Not to copy: no holidays, unclear edges, datetime with a time.
def add_business_days(date: datetime, days: int) -> datetime:
while days > 0:
date = date + timedelta(days=1)
if date.weekday() != 5 and date.weekday() != 6:
days -= 1
return date # negative days? ignored
The improved recipe
If you need United States federal holidays, generate them instead of typing them in every January:
Usage snippet:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Business-day arithmetic with a pluggable holiday calendar
Source: ImproveCode, Chapter 15, Recipe 15.4 "Business-Day Calculations"
Section: The improved recipe
Book page: 335-336 -- original C# listing
Converted from C# to Python.
DateOnly becomes datetime.date; IHolidayCalendar becomes a Protocol and the static
BusinessDays class becomes module functions.
"""
from collections.abc import Iterable
from datetime import date, timedelta
from typing import Protocol
class HolidayCalendar(Protocol):
def is_holiday(self, day: date) -> bool: ...
class HolidaySet:
def __init__(self, dates: Iterable[date]) -> None:
self._dates: frozenset[date] = frozenset(dates)
def is_holiday(self, day: date) -> bool:
return day in self._dates
def is_business_day(day: date, holidays: HolidayCalendar) -> bool:
return day.weekday() < 5 and not holidays.is_holiday(day)
def add(start: date, business_days: int, holidays: HolidayCalendar) -> date:
step = (business_days > 0) - (business_days < 0)
remaining = abs(business_days)
day = start
while remaining > 0:
day = day + timedelta(days=step)
if is_business_day(day, holidays):
remaining -= 1
return day
# Business days after start, up to and including end.
def between(start: date, end: date, holidays: HolidayCalendar) -> int:
if end < start:
return -between(end, start, holidays)
count = 0
d = start + timedelta(days=1)
while d <= end:
if is_business_day(d, holidays):
count += 1
d += timedelta(days=1)
return count
def next_or_same(day: date, holidays: HolidayCalendar) -> date:
while not is_business_day(day, holidays):
day = day + timedelta(days=1)
return day
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Compute observed US federal holidays for a year
Source: ImproveCode, Chapter 15, Recipe 15.4 "Business-Day Calculations"
Section: The improved recipe
Book page: 336-337 -- original C# listing
Converted from C# to Python.
DayOfWeek becomes the calendar module's weekday constants (Monday=0); the yield-return
iterator becomes a generator. calendar.monthrange replaces DateTime.DaysInMonth.
"""
import calendar
from collections.abc import Iterator
from datetime import date, timedelta
def for_year(year: int) -> Iterator[date]:
yield _observed(date(year, 1, 1))
yield _nth(year, 1, calendar.MONDAY, 3)
yield _nth(year, 2, calendar.MONDAY, 3)
yield _last(year, 5, calendar.MONDAY)
if year >= 2021:
yield _observed(date(year, 6, 19))
yield _observed(date(year, 7, 4))
yield _nth(year, 9, calendar.MONDAY, 1)
yield _nth(year, 10, calendar.MONDAY, 2)
yield _observed(date(year, 11, 11))
yield _nth(year, 11, calendar.THURSDAY, 4)
yield _observed(date(year, 12, 25))
def _observed(day: date) -> date:
match day.weekday():
case calendar.SATURDAY:
return day - timedelta(days=1)
case calendar.SUNDAY:
return day + timedelta(days=1)
case _:
return day
def _nth(year: int, month: int, weekday: int, n: int) -> date:
first = date(year, month, 1)
offset = (weekday - first.weekday() + 7) % 7
return first + timedelta(days=offset + (7 * (n - 1)))
def _last(year: int, month: int, weekday: int) -> date:
last = date(year, month, calendar.monthrange(year, month)[1])
offset = (last.weekday() - weekday + 7) % 7
return last - timedelta(days=offset)
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Build a three-year holiday set and compute a due date five business days out
Source: ImproveCode, Chapter 15, Recipe 15.4 "Business-Day Calculations"
Section: The improved recipe
Book page: 337 -- original C# listing
Converted from C# to Python.
LINQ Concat becomes itertools.chain.
"""
from datetime import date
from itertools import chain
from p335_r15_4_business_days_holiday_calendar import HolidaySet, add
from p336_r15_4_us_federal_holidays import for_year
def example() -> date:
holidays = HolidaySet(chain(for_year(2025), for_year(2026), for_year(2027)))
due = add(date(2026, 7, 1), 5, holidays) # 2026-07-09
return due
How it works
The calculation works on DateOnly, so a time of day can't push a date across midnight during conversion. IsBusinessDay is the single definition of a working day; change it once if your business works Saturdays.
Add steps one day at a time in either direction and counts only business days, so Add(date, -3, ...) goes back three working days. A loop sounds slow, but even a year of business days is a few hundred iterations, far below the cost of the database call that usually surrounds it.
Between uses the same convention as Add: it counts days after the start, up to and including the end. With that convention, if end is a business day, Add(start, Between(start, end)) returns end. Pick one convention, write it on the method, and test the edges. Most business-day bugs come down to a disagreement about whether the start day counts.
The holiday calendar is an interface so the source can vary: a HashSet built from code, a table loaded at startup, or a call to a calendar service. Hiding the lookup behind IsHoliday keeps the arithmetic free of I/O. In the example, July 3, 2026 is the observed Independence Day (July 4 falls on a Saturday), so five business days from July 1 lands on July 9.
UsFederalHolidays applies the federal observance rule: a holiday that falls on Saturday is observed on Friday, and one on Sunday on Monday. Note that when January 1 falls on a Saturday, the observed day is December 31 of the previous year, which is why the usage builds the set from three years.
Variations and pitfalls
- Your business holidays are rarely exactly the federal list. Banks follow the Federal Reserve calendar, which does not move Saturday holidays to Friday. Many companies add the day after Thanksgiving. Keep the calendar in a
dbo.Holidaytable that the business can maintain and load it into aHolidaySetat startup. - Different regions need different calendars. Make the calendar a parameter, never a static.
- For very large ranges, count whole weeks arithmetically and loop only over the remainder. Few business apps need it.
- In SQL, a calendar table with an
IsBusinessDaycolumn beats any function for reporting queries. Generate it from the same rules.