calendar Answers Month And Leap Questions
calendar.isleap, monthrange, and monthdatescalendar answer leap-year, month-length, and grid questions with locale-aware weekday names in one import.
Code
import calendar
# 闰年判断:四年一闰、逢百年不闰、逢四百年再闰
print("2024 leap:", calendar.isleap(2024), "| 2026 leap:", calendar.isleap(2026))
# monthrange 返回 (首日星期几, 当月天数),星期一记为 0
first_weekday, days = calendar.monthrange(2026, 2)
print("Feb 2026:", calendar.day_name[first_weekday], "starts,", days, "days")
leap_weekday, leap_days = calendar.monthrange(2024, 2)
print("Feb 2024:", leap_days, "days")
# monthdatescalendar 产出含前后月补位的完整周,正好用来渲染月历网格
weeks = calendar.Calendar(firstweekday=0).monthdatescalendar(2026, 2)
print("Feb 2026 weeks:", len(weeks))
print("grid from", weeks[0][0].isoformat(), "to", weeks[-1][-1].isoformat())Output
Captured from a sandboxed run of this snippet in the build pipeline.
2024 leap: True | 2026 leap: False
Feb 2026: Sunday starts, 28 days
Feb 2024: 29 days
Feb 2026 weeks: 5
grid from 2026-01-26 to 2026-03-01How it works
The file’s state is a handful of top-level bindings: weeks.
What to watch for
- Dependency check:
calendar— not built-in, must be present in the project.
Using it
Running the file prints labeled results such as 2024 leap:, Feb 2026:, Feb 2024: — each operation’s effect is visible in the output.
Interactive Tools for This Topic
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.Cron Next Runs CalculatorCompute the next scheduled run times for a standard five-field cron expression, supporting ranges, lists, steps, and day-of-week naming semantics.ISO Week CalculatorFind the ISO 8601 week number, ISO week-year, week start and end dates, and day of year for any calendar date, with strict date validation.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `weeks`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.