Parse an ISO 8601 date before a calendar calculation

Parse external date text into a date object before using it in calendar logic. This example accepts the ISO 8601 calendar-date string 2024-02-29, calls date.fromisoformat(), and then passes the parsed year and month to calendar.monthrange(). The result establishes that February 2024 has 29 days. It also prints the weekday number for the parsed date, where Monday is 0 and Thursday is 3.

Using the parsed object prevents calculations from depending on slices of a string or on assumptions about month length. fromisoformat() raises ValueError when its input is not a supported ISO date representation, so production code that accepts untrusted input should decide where to catch and report that error. Parsing a date alone does not add a time or time zone; use an aware datetime when the input describes an instant.

date.fromisoformat() has been available since Python 3.7. calendar.monthrange() returns a pair containing the weekday of day one and the number of days in the month; it does not validate arbitrary text itself. The fixed leap-day input makes the calculation deterministic, while the assertions check this particular result rather than every possible date. Consult the official date.fromisoformat() documentation and calendar.monthrange() documentation.

AI assistance disclosure: this article was drafted with AI assistance and should be reviewed for the application's input-validation needs.

import calendar
from datetime import date

iso_date = "2024-02-29"
parsed_date = date.fromisoformat(iso_date)
first_weekday, days_in_month = calendar.monthrange(
    parsed_date.year, parsed_date.month
)

assert parsed_date.weekday() == 3
assert first_weekday == 3
assert days_in_month == 29

print(f"{parsed_date.isoformat()} is weekday {parsed_date.weekday()}")
print(f"February has {days_in_month} days")
2024-02-29 is weekday 3
February has 29 days

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