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
days_in_year_pendulum.py
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:
usage_pendulum.py
print(number_of_days_in_year(2020)) # Prints 366
print(number_of_days_in_year(2021)) # Prints 365Explanation:
First, we define the start date to be the first day (1st of January) of the year we’re interested in:
example_pendulum_snippet.py
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_date_example.py
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:
days_diff_example.py
(end - start).in_days()Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow