Find the first and last day of a month
To find both boundaries of a month, construct day one directly and ask calendar.monthrange() how many days that month contains. This example uses March 2025. date(2025, 3, 1) supplies the first day, and the second item returned by monthrange(2025, 3) supplies 31 for the final day number. Constructing date(2025, 3, 31) then produces the correct last boundary without maintaining a separate list of month lengths.
The assertions check the complete ISO representations and the expected weekday values for this chosen month. Python's weekday convention is Monday equals 0, so Saturday is 5 and Monday is 0. Those numbers are useful for scheduling calculations, but they are not localized names; format labels separately if an interface needs them.
calendar.monthrange() handles leap years and returns (weekday_of_first_day, number_of_days). It expects valid integer year and month arguments, and date() will reject invalid components with ValueError. This pattern finds calendar-date boundaries, not time boundaries: if an API needs the final instant of a month in a particular zone, define its precision and time-zone rules explicitly. These functions are part of the standard library; see the calendar.monthrange() reference and the date constructor documentation.
AI assistance disclosure: this article was drafted with AI assistance and should be reviewed for the application's boundary conventions.
import calendar
from datetime import date
year = 2025
month = 3
first_day = date(year, month, 1)
first_weekday, number_of_days = calendar.monthrange(year, month)
last_day = date(year, month, number_of_days)
assert first_day.isoformat() == "2025-03-01"
assert last_day.isoformat() == "2025-03-31"
assert (first_weekday, first_day.weekday(), last_day.weekday()) == (5, 5, 0)
print(f"first: {first_day.isoformat()}")
print(f"last: {last_day.isoformat()}")
first: 2025-03-01
last: 2025-03-31
Comments
Post a Comment