How to compute number of days in a year in Python using Pendulum
Also see How to compute number of days in a year in Pandas
We can use the excellent pendulum
library to find the number of days in a given year
import pendulum
def number_of_days_in_year(year):
start = pendulum.date(year, 1, 1)
end = start.add(years=1)
return (end - start).in_days()
Usage example:
print(number_of_days_in_year(2020)) # Prints 366
print(number_of_days_in_year(2021)) # Prints 365
Explanation:
First, we define the start
date to be the first day (1st of January) of the year we’re interested in:
start = pendulum.date(year, 1, 1)
Now we use pendulum
‘s add
function to add exactly one year to that date. This will always result in the 1st of January of the year after the given year:
end = start.add(years=1)
The rest is simple: Just ask pendulum
to give us the number of days in the difference between end
and start
:
(end - start).in_days()