Find the next weekday from a given date

To find the next occurrence of a weekday, use the integer convention of date.weekday(): Monday is 0 through Sunday is 6. The function calculates the forward distance with modular arithmetic. The or 7 is important: a zero remainder means the input is already the target weekday, but this article’s “next” contract requires the following occurrence rather than the same date.

For the supplied Friday, 2026-05-01, the target value 0 means Monday. The distance is three days, producing Monday 2026-05-04. The two assertions check the resulting date and confirm that it is Monday. They do not prove that target values outside 0 through 6 are valid, so production code should validate externally supplied weekday numbers if they can be malformed.

This is calendar arithmetic, not a business-calendar calculation. It can return a public holiday and does not take working hours, user locale preferences, or a timestamp’s time zone into account. Use a date only when the input and output are date-only concepts; convert an instant to the intended local date before applying a local-calendar rule. The example uses Python standard-library date, timedelta, and weekday() and works on Python 3.2+.

The weekday numbering and date addition rules are documented in Python’s datetime reference.

AI-assistance disclosure: This article was drafted with AI assistance and should be reviewed in its application context.

from datetime import date, timedelta


def next_weekday(start, target):
    days = (target - start.weekday()) % 7 or 7
    return start + timedelta(days=days)

next_monday = next_weekday(date(2026, 5, 1), 0)

assert next_monday == date(2026, 5, 4)
assert next_monday.weekday() == 0

print(next_monday.isoformat())
print(next_monday.weekday())
2026-05-04
0

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic