Python date ranges
last modified November 19, 2026 Python 3.15
In this article we generate ranges of dates in Python. Reports run over the days of a month, payroll needs the working days between two dates, and booking systems must find overlapping stays. Python has no built-in range for dates, but a short generator function built on timedelta covers most cases.
The ranges in this article are half-open, like Python's range:
the start is included and the stop is excluded. Half-open ranges can be
joined without gaps or duplicates, and the length of a range is simply the
difference of its ends.
A range of days
A generator yields the days from the start up to, but not including, the stop.
from datetime import date, timedelta
def date_range(start, stop):
day = start
while day < stop:
yield day
day += timedelta(days=1)
for day in date_range(date(2026, 11, 26), date(2026, 12, 3)):
print(day, day.strftime("%a"))
days = list(date_range(date(2026, 1, 1), date(2027, 1, 1)))
print(len(days), days[0], days[-1])
The date_range function adds one day per step and stops before
stop. The first loop prints the seven days from Thursday,
November 26. Because the stop is excluded, the range from January 1, 2026
to January 1, 2027 holds exactly the 365 days of 2026.
$ python first_range.py 2026-11-26 Thu 2026-11-27 Fri 2026-11-28 Sat 2026-11-29 Sun 2026-11-30 Mon 2026-12-01 Tue 2026-12-02 Wed 365 2026-01-01 2026-12-31
Steps and reverse ranges
A step parameter makes the function useful for weeks or every
few days. A negative step walks backwards.
from datetime import date, timedelta
def date_range(start, stop, step=timedelta(days=1)):
if not step:
raise ValueError("step must not be zero")
day = start
while (day < stop) if step > timedelta(0) else (day > stop):
yield day
day += step
start = date(2026, 11, 2)
stop = date(2026, 12, 31)
print([str(d) for d in date_range(start, stop, timedelta(weeks=2))])
print([d.day for d in date_range(start, date(2026, 11, 20), timedelta(days=3))])
print([d.day for d in date_range(date(2026, 11, 7), start, timedelta(days=-1))])
print(list(date_range(stop, start)))
try:
list(date_range(start, stop, timedelta(0)))
except ValueError as e:
print("ValueError:", e)
The loop condition depends on the sign of the step: a positive step runs
while the day is before the stop, a negative step while it is after it. A
zero timedelta is false, so not step catches it,
which would otherwise loop forever. When the start is past the stop, the
range is empty, just like range(10, 5).
$ python steps.py ['2026-11-02', '2026-11-16', '2026-11-30', '2026-12-14', '2026-12-28'] [2, 5, 8, 11, 14, 17] [7, 6, 5, 4, 3] [] ValueError: step must not be zero
Hourly ranges and daylight saving time
Datetime ranges work the same way, but in a time zone with daylight saving time, the result depends on how we add the hours.
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
local = ZoneInfo("Europe/Bratislava")
hour = timedelta(hours=1)
start = datetime(2026, 10, 25, 1, 0, tzinfo=local)
stop = datetime(2026, 10, 25, 4, 0, tzinfo=local)
wall = []
t = start
while t < stop:
wall.append(t)
t += hour
print(" ".join(f"{t:%H:%M %Z}" for t in wall))
real = []
t = start.astimezone(UTC)
while t < stop:
real.append(t.astimezone(local))
t += hour
print(" ".join(f"{t:%H:%M %Z}" for t in real))
print((stop - start) / hour, len(wall), len(real))
Adding a timedelta to an aware datetime changes the wall-clock
time and keeps the zone, so the first range goes 1:00, 2:00, 3:00 and skips
the repeated 2:00 hour on October 25, 2026. Stepping in UTC and converting
each value to local time gives every real hour, including 2:00 CEST and 2:00
CET. Subtraction of two datetimes with the same tzinfo also
ignores the offset change and reports three hours, although four have
passed. The zoneinfo article explains these
rules.
$ python hourly.py 01:00 CEST 02:00 CEST 03:00 CET 01:00 CEST 02:00 CEST 02:00 CET 03:00 CET 3.0 3 4
Monthly ranges
Months have different lengths, so a monthly range needs month arithmetic that clamps the day, as shown in the timedelta article. How we apply it matters.
from datetime import date
def days_in_month(year, month):
if month == 12:
return 31
return (date(year, month + 1, 1) - date(year, month, 1)).days
def add_months(d, months):
year, month = divmod(d.year * 12 + d.month - 1 + months, 12)
day = min(d.day, days_in_month(year, month + 1))
return date(year, month + 1, day)
start = date(2026, 1, 31)
chained = [start]
for _ in range(5):
chained.append(add_months(chained[-1], 1))
print([str(d) for d in chained])
anchored = [add_months(start, n) for n in range(6)]
print([str(d) for d in anchored])
renewals = [add_months(date(2028, 2, 29), 12 * n) for n in range(5)]
print([str(d) for d in renewals])
Chaining one-month steps loses the day: January 31 becomes February 28,
and every later date stays on the 28th. Computing each date from the start
with add_months(start, n) keeps the end of the month. The same
applies to yearly ranges: a contract renewed on February 29 falls on
February 28 in common years and returns to February 29 in 2032.
$ python monthly.py ['2026-01-31', '2026-02-28', '2026-03-28', '2026-04-28', '2026-05-28', '2026-06-28'] ['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30', '2026-05-31', '2026-06-30'] ['2028-02-29', '2029-02-28', '2030-02-28', '2031-02-28', '2032-02-29']
Month starts and ends
The helpers are now complete enough to move them into a module, so that the following examples can import them.
from datetime import date, timedelta
ONE_DAY = timedelta(days=1)
def date_range(start, stop, step=ONE_DAY):
if not step:
raise ValueError("step must not be zero")
day = start
while (day < stop) if step > timedelta(0) else (day > stop):
yield day
day += step
def days_in_month(year, month):
if month == 12:
return 31
return (date(year, month + 1, 1) - date(year, month, 1)).days
def add_months(d, months):
year, month = divmod(d.year * 12 + d.month - 1 + months, 12)
day = min(d.day, days_in_month(year, month + 1))
return date(year, month + 1, day)
def month_end(d):
return d.replace(day=days_in_month(d.year, d.month))
The dateranges module holds the generator, the month
arithmetic, and a new month_end function, which replaces the
day with the length of the month.
from datetime import date
from dateranges import add_months, month_end
first = date(2026, 1, 1)
for n in range(12):
start = add_months(first, n)
end = month_end(start)
print(f"{start:%b} {start} .. {end} {end.day} days")
payday = date(2026, 1, 31)
print([str(month_end(add_months(payday, n))) for n in range(4)])
The program prints the first and last day of every month of 2026. The last line shows month-end dates of a payroll that runs on the last day of each month.
$ python month_ends.py Jan 2026-01-01 .. 2026-01-31 31 days Feb 2026-02-01 .. 2026-02-28 28 days Mar 2026-03-01 .. 2026-03-31 31 days Apr 2026-04-01 .. 2026-04-30 30 days May 2026-05-01 .. 2026-05-31 31 days Jun 2026-06-01 .. 2026-06-30 30 days Jul 2026-07-01 .. 2026-07-31 31 days Aug 2026-08-01 .. 2026-08-31 31 days Sep 2026-09-01 .. 2026-09-30 30 days Oct 2026-10-01 .. 2026-10-31 31 days Nov 2026-11-01 .. 2026-11-30 30 days Dec 2026-12-01 .. 2026-12-31 31 days ['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30']
Weekly ranges
Weekly schedules usually start on a fixed weekday, so the range must first be aligned to that day.
from datetime import date, timedelta
from dateranges import date_range
def next_weekday(d, weekday):
return d + timedelta(days=(weekday - d.weekday()) % 7)
start = date(2026, 11, 19)
stop = date(2027, 1, 1)
first_monday = next_weekday(start, 0)
mondays = list(date_range(first_monday, stop, timedelta(weeks=1)))
print([d.strftime("%b %d") for d in mondays])
print(next_weekday(date(2026, 11, 23), 0))
print(next_weekday(start, 4), next_weekday(start, 6))
for d in date_range(start, start + timedelta(days=7)):
print(d.strftime("%a"), "->", d - timedelta(days=d.weekday()))
The next_weekday function moves a date forward to the given
weekday, where 0 is Monday; the modulo returns 0 when the date already is
that weekday. With the aligned start, a one-week step yields every Monday
until the end of the year. The loop at the end goes in the other direction
and maps each day to the Monday that starts its week, which is how weekly
reports group days.
$ python mondays.py ['Nov 23', 'Nov 30', 'Dec 07', 'Dec 14', 'Dec 21', 'Dec 28'] 2026-11-23 2026-11-20 2026-11-22 Thu -> 2026-11-16 Fri -> 2026-11-16 Sat -> 2026-11-16 Sun -> 2026-11-16 Mon -> 2026-11-23 Tue -> 2026-11-23 Wed -> 2026-11-23
Working days
Filtering a range by weekday gives the working days. Monday to Friday are the weekdays 0 to 4.
from datetime import date
from dateranges import add_months, date_range
def is_weekday(d):
return d.weekday() < 5
start = date(2026, 11, 1)
stop = add_months(start, 1)
weekdays = [d for d in date_range(start, stop) if is_weekday(d)]
print(len(weekdays), weekdays[0], weekdays[-1])
counts = []
for n in range(12):
month = add_months(date(2026, 1, 1), n)
days = date_range(month, add_months(month, 1))
counts.append(f"{month:%b} {sum(is_weekday(d) for d in days)}")
print(", ".join(counts))
November 2026 has 21 weekdays, from Monday, November 2 to Monday, November
30. The loop counts the weekdays of every month of the year. Booleans are
integers in Python, so sum over the results of
is_weekday counts the true values.
$ python working_days.py 21 2026-11-02 2026-11-30 Jan 22, Feb 20, Mar 22, Apr 22, May 21, Jun 22, Jul 23, Aug 21, Sep 22, Oct 22, Nov 21, Dec 23
Holidays
Real working days also exclude holidays. We keep them in a set, which gives
fast lookups, in a small workdays module.
from datetime import date
HOLIDAYS = {
date(2026, 1, 1), date(2026, 4, 3), date(2026, 4, 6),
date(2026, 5, 1), date(2026, 12, 24), date(2026, 12, 25),
date(2026, 12, 31), date(2027, 1, 1),
}
def is_working_day(d, holidays=HOLIDAYS):
return d.weekday() < 5 and d not in holidays
The set lists the holidays of a fictional company for 2026 and New Year's
Day of 2027. The holidays parameter lets callers pass a
different calendar.
from datetime import date
from dateranges import add_months, date_range
from workdays import is_working_day
december = date(2026, 12, 1)
month = list(date_range(december, add_months(december, 1)))
days = [d for d in month if is_working_day(d)]
print(len(days))
print(" ".join(f"{d.day:2}" for d in days))
off = [d for d in month if d.weekday() < 5 and not is_working_day(d)]
print("holidays on weekdays:", [d.strftime("%a %d") for d in off])
print(sum(is_working_day(d, set()) for d in month))
December 2026 has 23 weekdays, but the 24th, 25th, and 31st are holidays, which leaves 20 working days. Passing an empty set gives back the plain weekday count.
$ python december.py 20 1 2 3 4 7 8 9 10 11 14 15 16 17 18 21 22 23 28 29 30 holidays on weekdays: ['Thu 24', 'Fri 25', 'Thu 31'] 23
Adding business days
Delivery dates and payment terms are often given in business days: an order ships in five working days.
from datetime import date, timedelta
from workdays import HOLIDAYS, is_working_day
def add_business_days(d, n, holidays=HOLIDAYS):
step = timedelta(days=1 if n >= 0 else -1)
remaining = abs(n)
while remaining:
d += step
if is_working_day(d, holidays):
remaining -= 1
return d
ordered = date(2026, 12, 21)
for n in (1, 3, 5, 10):
due = add_business_days(ordered, n)
print(f"+{n:<2} {due} {due:%a}")
print(add_business_days(date(2026, 4, 7), -2))
print(add_business_days(date(2026, 11, 21), 1))
The function moves one day at a time and counts only working days, until the requested number is reached. Ten business days after Monday, December 21 is January 8, because the holidays and two weekends fall in between. A negative count goes back: two business days before Tuesday, April 7, skips Easter Monday and Good Friday. Saturday plus one business day is Monday.
$ python add_business_days.py +1 2026-12-22 Tue +3 2026-12-28 Mon +5 2026-12-30 Wed +10 2027-01-08 Fri 2026-04-01 2026-11-23
Counting without a loop
Looping over every day is simple but slow for long periods. The weekdays of a range can be computed from the number of full weeks.
from datetime import date, timedelta
from dateranges import date_range
from workdays import HOLIDAYS, is_working_day
def count_weekdays(start, stop):
weeks, rest = divmod((stop - start).days, 7)
first = start.weekday()
return weeks * 5 + sum((first + i) % 7 < 5 for i in range(rest))
def count_working_days(start, stop, holidays=HOLIDAYS):
closed = sum(start <= d < stop and d.weekday() < 5 for d in holidays)
return count_weekdays(start, stop) - closed
print(count_working_days(date(2026, 1, 1), date(2027, 1, 1)))
print(count_working_days(date(2026, 11, 19), date(2026, 12, 24)))
origin = date(2026, 1, 1)
for a in range(0, 380, 7):
for b in range(a, 380, 5):
start, stop = origin + timedelta(days=a), origin + timedelta(days=b)
loop = sum(is_working_day(d) for d in date_range(start, stop))
assert loop == count_working_days(start, stop), (start, stop)
print("formula agrees with the loop")
Each full week contains five weekdays; only the remaining zero to six days
need checking. Holidays that fall on weekdays inside the range are then
subtracted. The year 2026 has 254 working days in our company. The nested
loops compare the formula with the simple loop for hundreds of ranges, and
the assert would stop the program on the first difference.
$ python count_working.py 254 25 formula agrees with the loop
Splitting a range into months
Reports and database queries often process a long period month by month. The period is cut at month boundaries.
from datetime import date
from dateranges import add_months
def month_chunks(start, stop):
chunk = start
while chunk < stop:
first = chunk.replace(day=1)
end = min(add_months(first, 1), stop)
yield chunk, end
chunk = end
for begin, end in month_chunks(date(2026, 10, 15), date(2027, 2, 10)):
print(f"{begin} .. {end} {(end - begin).days:2} days")
print(list(month_chunks(date(2026, 11, 3), date(2026, 11, 20))))
print(list(month_chunks(date(2026, 11, 1), date(2026, 11, 1))))
The first chunk starts on October 15 and ends at the beginning of November; the following chunks are whole months, and the last one ends at the stop. Because the chunks are half-open, each day belongs to exactly one of them, and the day counts add up to the length of the period. An empty range gives no chunks.
$ python chunks.py 2026-10-15 .. 2026-11-01 17 days 2026-11-01 .. 2026-12-01 30 days 2026-12-01 .. 2027-01-01 31 days 2027-01-01 .. 2027-02-01 31 days 2027-02-01 .. 2027-02-10 9 days [(datetime.date(2026, 11, 3), datetime.date(2026, 11, 20))] []
Overlapping ranges
Two ranges overlap when the later start is before the earlier stop. This detects double bookings.
from datetime import date
def overlap(a, b):
start = max(a[0], b[0])
stop = min(a[1], b[1])
return (start, stop) if start < stop else None
bookings = {
"Alice": (date(2026, 12, 20), date(2026, 12, 27)),
"Bob": (date(2026, 12, 27), date(2027, 1, 3)),
"Carol": (date(2026, 12, 23), date(2026, 12, 29)),
}
names = list(bookings)
for i, first in enumerate(names):
for second in names[i + 1:]:
common = overlap(bookings[first], bookings[second])
if common:
nights = (common[1] - common[0]).days
print(f"{first} and {second}: {common[0]} .. {common[1]}, {nights} nights")
else:
print(f"{first} and {second}: no clash")
request = (date(2026, 12, 18), date(2026, 12, 21))
print(any(overlap(request, b) for b in bookings.values()))
The overlap function returns the common part of two ranges or
None. Each booking runs from the arrival day to the departure
day, so Alice leaving on December 27 and Bob arriving that day do not clash.
Carol's stay overlaps both of them. The last line checks a new request
against all bookings.
$ python overlaps.py Alice and Bob: no clash Alice and Carol: 2026-12-23 .. 2026-12-27, 4 nights Bob and Carol: 2026-12-27 .. 2026-12-29, 2 nights True
Source
calendar – General calendar-related functions
In this article we have generated ranges of days, hours, weeks, and months,
counted working days, skipped holidays, and compared ranges. Recurrence
rules such as "the last Friday of every month" are easier with
rrule from the dateutil
library. See also Python datetime,
Python calendar, and
Python ISO weeks.
Author
List all Python tutorials.