Python calendar.leapdays() Function



The Python calendar.leapdays() function is used to determine the number of leap years in a given range of years.

This function counts the leap years between two given years (excluding the end year).

Syntax

Following is the syntax of the Python calendar.leapdays() function −

calendar.leapdays(year1, year2)

Parameters

This function accepts the following parameters −

  • year1: The starting year (inclusive).
  • year2: The ending year (exclusive).

Return Value

This function returns an integer representing the number of leap years between the given years (excluding the end year).

Example: Counting Leap Years in a Decade

In this example, we count the leap years between 2000 and 2010 using the calendar.leapdays() function −

import calendar

# Count leap years from 2000 to 2010 (excluding 2010)
leap_count = calendar.leapdays(2000, 2010)

print("Number of leap years from 2000 to 2010:", leap_count)  

We get the output as shown below −

Number of leap years from 2000 to 2010: 3

Example: Counting Leap Years in a Century

Here, we use the leapdays() function to count the leap years between 1900 and 2000 −

import calendar

# Count leap years from 1900 to 2000 (excluding 2000)
leap_count = calendar.leapdays(1900, 2000)

print("Number of leap years from 1900 to 2000:", leap_count) 

Following is the output of the above code −

Number of leap years from 1900 to 2000: 24

Example: Counting Leap Years Across Two Centuries

Now, we count the leap years from 1800 to 2025 i.e. across 2 centuries −

import calendar

# Count leap years from 1800 to 2025 (excluding 2025)
leap_count = calendar.leapdays(1800, 2025)

print("Number of leap years from 1800 to 2025:", leap_count)

Following is the output obtained −

Number of leap years from 1800 to 2025: 55

Example: Counting Leap Years in a Short Range

In the example below, we are checking the number of leap years in a short range between 2016 and 2024 −

import calendar

# Count leap years from 2016 to 2024 (excluding 2024)
leap_count = calendar.leapdays(2016, 2024)

print("Number of leap years from 2016 to 2024:", leap_count) 

The result produced is as shown below −

Number of leap years from 2016 to 2024: 2
python_date_time.htm
Advertisements