Python calendar 实战:月长、闰年与完整周网格的五个可运行示例

10-23 6阅读

本文用五个可独立运行的标准库程序,拆清月长、闰年、周起点和补齐周这四件事。所有检查都使用显式 require,开启优化选项仍然执行;程序只计算并打印,不读写文件、不联网,也不读取当前时间。输出已在 Python 3.12 与 3.13 的普通和优化模式逐字核对。

Python calendar 实战:月长、闰年与完整周网格的五个可运行示例

配图为模型生成的日历网格概念示意,不是软件截图,不代表某个具体月份。

1 先确认月长与闰年规则

做月度报表或日期选择器时,应先确定月份事实,再决定界面如何补齐空格。monthrange 返回两个值:月初星期编号和当月天数。星期一固定为零,星期日为六;第二个值才是月长,不能把整个结果当成天数。下面用同一组二月数据核对世纪边界。闰年须能被四整除,遇整百年还须能被四百整除,因此一九〇〇年不是闰年,二〇〇〇年是。

import calendar


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def gregorian_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


require(calendar.monthrange(2024, 2) == (3, 29), "2024 February")
require(calendar.monthrange(2023, 2) == (2, 28), "2023 February")
require(calendar.monthrange(1900, 2) == (3, 28), "1900 February")
require(calendar.monthrange(2000, 2) == (1, 29), "2000 February")
require(not calendar.isleap(1900), "1900 is common")
require(calendar.isleap(2000), "2000 is leap")
require(calendar.isleap(2024), "2024 is leap")
require(not calendar.isleap(2100), "2100 is common")
require(all(gregorian_leap(y) == calendar.isleap(y)
            for y in range(1800, 2401)), "leap rule")
require(calendar.leapdays(1900, 2000) == 24, "exclude 2000")
require(calendar.leapdays(1900, 2001) == 25, "include 2000")
require(calendar.leapdays(2000, 2001) == 1, "one-year range")
require(calendar.leapdays(2000, 2000) == 0, "empty range")

for year in (1900, 2000, 2024):
    weekday, count = calendar.monthrange(year, 2)
    print(year, int(weekday), count, calendar.isleap(year))
print("leap counts:", calendar.leapdays(1900, 2000),
      calendar.leapdays(1900, 2001))

准确输出:

1900 3 28 False
2000 1 29 True
2024 3 29 True
leap counts: 24 25

leapdays 的区间左闭右开,结束年份不计入。统计一九〇〇年至二〇〇〇年时,如果业务要求包含二〇〇〇年,结束参数应传二〇〇一年。把区间含义写进测试名称,比只看一个统计结果更容易发现边界偏差。

2 把每周起点放进实例

同一个月份可以有不同的网格行数。二〇二四年九月从星期日开始:星期一排第一列需要六行,星期日排第一列只需五行。每行仍然都是七格。下面分别构造两个 Calendar,检查完整日期序列,也检查模块的全局设置没有变化。

import calendar


def require(condition, message):
    if not condition:
        raise AssertionError(message)


original = calendar.firstweekday()
monday = calendar.Calendar(firstweekday=calendar.MONDAY)
sunday = calendar.Calendar(firstweekday=calendar.SUNDAY)
m = monday.monthdayscalendar(2024, 9)
s = sunday.monthdayscalendar(2024, 9)
require(monday.firstweekday == 0, "Monday instance")
require(sunday.firstweekday == 6, "Sunday instance")
require(list(monday.iterweekdays()) == list(range(7)), "Monday columns")
require(list(sunday.iterweekdays()) == [6, 0, 1, 2, 3, 4, 5], "Sunday columns")
require(len(m) == 6, "six Monday-first rows")
require(len(s) == 5, "five Sunday-first rows")
require(all(len(row) == 7 for row in m + s), "full weeks")
require(m[0] == [0, 0, 0, 0, 0, 0, 1], "Monday first row")
require(m[-1] == [30, 0, 0, 0, 0, 0, 0], "Monday last row")
require(s[0] == [1, 2, 3, 4, 5, 6, 7], "Sunday first row")
require(s[-1] == [29, 30, 0, 0, 0, 0, 0], "Sunday last row")
require([d for row in m for d in row if d] == list(range(1, 31)), "Monday days")
require([d for row in s for d in row if d] == list(range(1, 31)), "Sunday days")
require(calendar.firstweekday() == original, "global state unchanged")
print("Monday:", len(m), m[0], m[-1])
print("Sunday:", len(s), s[0], s[-1])

准确输出:

Monday: 6 [0, 0, 0, 0, 0, 0, 1] [30, 0, 0, 0, 0, 0, 0]
Sunday: 5 [1, 2, 3, 4, 5, 6, 7] [29, 30, 0, 0, 0, 0, 0]

在组件、报表和接口共用进程时,实例配置让调用关系更清楚。不要为了一个星期日开头的控件,修改整个模块的周起点。渲染器还应从该实例获取列顺序,避免数据已经换序,表头却仍从星期一开始。

3 补零日号与真实日期分开处理

itermonthdays 给的是日号;月外格子一律用零占位。这里的零不是上个月最后一天,也不是格式化后的字符串零零。itermonthdates 则返回真实日期对象,自动带上需要的相邻月份。两者都覆盖完整周,所以二月的网格可能包含三月日期。

import calendar
from datetime import date, timedelta


def require(condition, message):
    if not condition:
        raise AssertionError(message)


cal = calendar.Calendar(firstweekday=calendar.MONDAY)
days = list(cal.itermonthdays(2024, 2))
dates = list(cal.itermonthdates(2024, 2))
require(len(days) == 35, "five full weeks")
require(len(dates) == len(days), "aligned grids")
require(days[:7] == [0, 0, 0, 1, 2, 3, 4], "leading placeholders")
require(days[-7:] == [26, 27, 28, 29, 0, 0, 0], "trailing placeholders")
require(days.count(0) == 6, "six placeholders")
require(dates[0] == date(2024, 1, 29), "real first date")
require(dates[-1] == date(2024, 3, 3), "real last date")
require(sum(d.month == 2 for d in dates) == 29, "target month count")
require(all(b - a == timedelta(days=1)
            for a, b in zip(dates, dates[1:])), "consecutive dates")
require(all(n == (d.day if d.month == 2 else 0)
            for n, d in zip(days, dates)), "placeholder mapping")
print("day numbers:", days[:7], days[-7:])
print("date span:", dates[0].isoformat(), dates[-1].isoformat())
print("cells:", len(dates), "in month:", sum(d.month == 2 for d in dates))

准确输出:

day numbers: [0, 0, 0, 1, 2, 3, 4] [26, 27, 28, 29, 0, 0, 0]
date span: 2024-01-29 2024-03-03
cells: 35 in month: 29

示例先检查两个序列等长,再逐格确认映射关系。统计本月记录时必须筛选月份,不能把网格长度当作月长。需要跨年复用筛选逻辑时,请同时比较年份和月份。用于展示的空白格可由零映射得到,用于绑定事件的键则宜保存完整日期。

4 需要年月日与星期时使用四元组

itermonthdays4 每格提供年、月、日、星期四个字段,相邻月也保留真实年月日,不会退化成零。星期日开头仅改变排列顺序,并不重新编号;星期日仍为六,随后才是零到五。下面把四元组转换为日期做交叉验证,转换只适用于日期对象允许的年份。

import calendar
from datetime import date


def require(condition, message):
    if not condition:
        raise AssertionError(message)


cal = calendar.Calendar(firstweekday=calendar.SUNDAY)
cells = list(cal.itermonthdays4(2024, 2))
require(len(cells) == 35, "five weeks")
require(all(len(cell) == 4 for cell in cells), "four fields")
require(cells[0] == (2024, 1, 28, 6), "previous month")
require(cells[-1] == (2024, 3, 2, 5), "next month")
require([w for y, m, d, w in cells[:7]] == [6, 0, 1, 2, 3, 4, 5], "weekday order")
require(sum((y, m) == (2024, 2) for y, m, d, w in cells) == 29, "February cells")
require(all(d > 0 for y, m, d, w in cells), "no zero placeholders")
require(all(date(y, m, d).weekday() == w for y, m, d, w in cells), "weekday labels")
require([date(y, m, d) for y, m, d, w in cells]
        == list(cal.itermonthdates(2024, 2)), "same real dates")
print("first:", cells[0], "last:", cells[-1])
print("weekdays:", [w for y, m, d, w in cells[:7]])
print("in month:", sum((y, m) == (2024, 2) for y, m, d, w in cells))

准确输出:

first: (2024, 1, 28, 6) last: (2024, 3, 2, 5)
weekdays: [6, 0, 1, 2, 3, 4, 5]
in month: 29

四元组适合传递结构化网格数据:界面可以根据年月判断灰显,根据星期决定列位置。不要只取日号建立索引,否则相邻两个月同名日号会撞键;也不要把列索引误当成星期编号。

5 把输入与日期对象边界纳入测试

月份参数应是合法的月份整数,一到十二。示例验证零和十三触发 IllegalMonthError,并核对异常保留的错误月份;在本文测试版本中,它也是 ValueError 子类。代码按准确异常类型检查,不依赖英文报错措辞。

import calendar
from datetime import date


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def raises_exact(expected, operation):
    try:
        operation()
    except Exception as error:
        require(type(error) is expected, "unexpected exception type")
        return error
    raise AssertionError("expected exception was not raised")


bad0 = raises_exact(calendar.IllegalMonthError,
                    lambda: calendar.monthrange(2024, 0))
bad13 = raises_exact(calendar.IllegalMonthError,
                     lambda: calendar.monthrange(2024, 13))
require(bad0.month == 0, "invalid month retained")
require(bad13.month == 13, "invalid month retained")
require(isinstance(bad0, ValueError), "ValueError subclass")
require(date.min.year == 1, "minimum date year")
require(date.max.year == 9999, "maximum date year")
raises_exact(ValueError, lambda: date(0, 1, 1))
raises_exact(ValueError, lambda: date(10000, 1, 1))
monday = calendar.Calendar(firstweekday=calendar.MONDAY)
sunday = calendar.Calendar(firstweekday=calendar.SUNDAY)
require(list(monday.itermonthdates(1, 1))[0] == date.min, "safe lower edge")
raises_exact(ValueError, lambda: list(sunday.itermonthdates(1, 1)))
raises_exact(ValueError, lambda: list(monday.itermonthdates(9999, 12)))
low = list(sunday.itermonthdays4(1, 1))
high = list(monday.itermonthdays4(9999, 12))
require(low[0] == (0, 12, 31, 6), "tuple can represent year zero")
require(high[-1] == (10000, 1, 2, 6), "tuple can represent year 10000")
require(len(low) % 7 == 0 and len(high) % 7 == 0, "boundary full weeks")
require(calendar.monthrange(0, 2) == (1, 29), "extended Gregorian year")
print("invalid months:", type(bad0).__name__, type(bad13).__name__)
print("date years:", date.min.year, date.max.year)
print("boundary tuples:", low[0], high[-1])
print("date padding errors: ValueError ValueError")

准确输出:

invalid months: IllegalMonthError IllegalMonthError
date years: 1 9999
boundary tuples: (0, 12, 31, 6) (10000, 1, 2, 6)
date padding errors: ValueError ValueError

date 对象允许的年份为一至九九九九,但完整周可能跨出这个范围。最低年份一月按星期日开头会补到零年,最高年份十二月按星期一开头会补到一万年;消费日期迭代器时因此抛出 ValueError。四元组方法不受 date 年份范围约束,所以仍能返回这些边界格。提前转换成列表,是为了让惰性迭代中的错误在本例检查点发生。

使用边界

最后要划清用途:这里计算的是向前后延伸的公历日历,不是地区历史改历记录。星期六日也不等于法定休息日,节假日与调休需要独立数据。跨时区会议、夏令时转换和定时执行属于另一层问题,不能由一张月份网格推导。先选清楚日号、日期或四元组,再处理显示和业务规则,能减少大多数日历边缘错误。

一手参考

Python 3.13 calendar 文档;Python 3.12 calendar 文档;date 对象与范围;CPython calendar 实现。文档核验于北京时间二〇二六年十月二十三日。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。