应直接使用 calendar.isleap() 判断闰年,它准确实现公历规则、线程安全、性能优且自 Python 2.3 起稳定兼容,避免手写逻辑出错或误用类型。
直接用 calendar.isleap() 判定闰年,别自己写逻辑
Python 的 calendar.isleap() 是最可靠、最省事的闰年判断方式。它封装了格里高利历(公历)全部规则:能被 4 整除但不能被 100 整除,或能被 400 整除。自己手写条件容易漏掉 year % 400 == 0 这个例外,尤其在处理 1900、2000、2100 这类边界年份时出错。
实操建议:
-
calendar.isleap()接收一个整数年份,返回True或False,不接受字符串或浮点数——传入"2000"会抛TypeError - 无需导入其他模块,只写
import calendar即可调用 - 该函数是纯计算,无副作用,线程安全,可放心用于批量年份校验
常见错误:把 isleap() 当成类方法或误拼函数名
错误现象包括:AttributeError: module 'calendar' has no attribute 'IsLeap'、calendar.isleap(2024) 返回 None(其实是没 import 或写错了模块名)、或误以为要先实例化 calendar.Calendar() 才能用。
正确做法只有这一种:
import calendar print(calendar.isleap(2000)) # True print(calendar.isleap(1900)) # False print(calendar.isleap(2100)) # False print(calendar.isleap(2024)) # True
注意:isleap 是小写,不是 isLeap 或 IsLeap;它属于 calendar 模块顶层函数,和 calendar.TextCalendar 之类无关。
和 datetime.date().year 混用时要注意类型转换
如果你已有 datetime.date 对象,想判断它所在年份是否为闰年,别直接传 date 对象给 isleap()——它只认整数。
Python 3.14.3
微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。
正确写法:
-
calendar.isleap(my_date.year)—— 取.year属性转为整数 - 不要写
calendar.isleap(my_date),会报TypeError: unsupported operand type(s) for %: 'datetime.date' and 'int' - 也不建议用
int(str(my_date.year))这类多余转换,.year本来就是int
性能与兼容性:从 Python 2.3 起就稳定,且几乎无开销
calendar.isleap() 内部只是几个取模运算,执行一次耗时约 0.03 μs(百万分之三毫秒),比手写 year % 4 == 0 and year % 100 != 0 or year % 400 == 0 还略快一点——因为 CPython 对这个函数做了底层优化。
兼容性方面:
- Python 2.3+ 和所有 Python 3.x 版本均支持
- PyPy、MicroPython(部分移植版)也基本兼容
- 没有依赖系统时区或 locale 设置,结果确定、可预测
真正容易被忽略的是:它只按公历规则算,不处理儒略历、农历或自定义历法。如果业务涉及历史日期(如 1582 年前的欧洲日期),得额外确认历法背景——isleap() 默认不为此负责。