Date Constructor Rejects Impossible Dates

date(year, month, day) validates on construction: impossible dates raise ValueError with the exact rule instead of rolling into the next month.

PythonForm Validation

Code

pythonsnippet
18 lines
from datetime import date

# date validates its components at construction time: impossible
# dates raise ValueError naming the broken rule instead of rolling
# over into the next month
def load_date(year, month, day):
    try:
        return date(year, month, day)
    except ValueError as error:
        return f'rejected: {error}'


print(load_date(2026, 11, 21))
print(load_date(2026, 2, 30))   # February never has 30 days
print(load_date(2025, 13, 1))   # months run 1..12
print(load_date(2025, 3, 0))    # days run 1..31
print(load_date(2024, 2, 29))   # leap year accepts Feb 29
print(load_date(2025, 2, 29))   # non-leap year rejects it

Output

Captured from a sandboxed run of this snippet in the build pipeline.

2026-11-21
rejected: day is out of range for month
rejected: month must be in 1..12
rejected: day is out of range for month
2024-02-29
rejected: day is out of range for month

How it works

The whole behavior is carried by the function load_date.

A ValueError is raised unconditionally at its raise site — no input check sits in front of it.

What to watch for

  • No packages pulled in; the language’s built-in APIs carry all of the work here.

Using it

Entry signature: def load_date(year, month, day)

load_date is the public entry point; everything else in the file exists to support it.

The key statements, annotated

def load_date(year, month, day):
    try:
        return date(year, month, day)
    except ValueError as error:
        return f'rejected: {error}'

Interactive Tools for This Topic

FAQ

What triggers the exception?
No. The `ValueError` is not behind any guard — it triggers purely on reaching that line of code.
Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `load_date` at load time.