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.

PythonData Integrity

Code

pythonsnippet
16 lines
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-01

How 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

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`.