如何在 Python 中獲取指定年份範圍內的閏年總數?


在本文中,我們將討論如何在 Python 中查詢指定年份範圍內閏年的數量。

leapdays()

除了允許像程式一樣生成日曆之外,calendar 模組還提供了更多有用的與日曆相關的任務。Calendar 模組中定義的函式和類使用的理想化日曆是當前的公曆,在兩個方向上無限延伸。

對於簡單的文字日曆,Python 中的 calendar 模組提供了 calendar.leapdays() 函式。

語法

leapdays() 方法的語法如下。

leapdays()

上述函式接受兩個引數;它們是 -

  • year1:表示範圍的起始年份。
  • year2:表示結束年份或範圍的結束。

返回值

leapdays() 函式接受上述引數並返回指定年份範圍內閏年的數量。

示例

在以下示例程式碼中,我們使用 Python 中 calendar 模組提供的 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

更新於: 2022年9月8日

502 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.