Python 如何获取指定范围内年份的闰年总数
本文将讨论如何在Python中找到指定年份范围内的闰年数量。
leapdays()
calendar模块除了允许生成日历之外,还提供了更多有用的与日历相关的任务。Calendar模块中的函数和类所使用的理想化日历是当前的公历在两个方向上无限延展。
对于简单的文本日历,Python中的calendar模块提供了calendar.leapdays()函数。
语法
leapdays()方法的语法如下所示。
leapdays()
上述函数有两个参数;它们是−
- year1:这代表了范围的起始年份。
- year2:这代表了范围的结束年份。
返回值
leapdays() 函数接受上述参数并返回指定年份范围内闰年的数量。
示例
在以下示例代码中,我们使用 python 中 calender 模块提供的 leapdays() 函数来找到指定年份范围内闰年的数量。
import calendar
print("The number of leapdays in the range of 2011 to 2030 is:")
print(calendar.leapdays(2011, 2030))
print("The number of leapdays in the range of 2001 to 2100 is:")
print(calendar.leapdays(2001, 2100))
输出
上述代码的输出结果如下。
The number of leapdays in the range of 2011 to 2030 is:
5
The number of leapdays in the range of 2001 to 2100 is:
24