How to compute number of days in a year in Pandas

In our previous post we showed how to used the pendulum library in order to compute the number of days in a given year using the pendulum library.

This post shows how to achieve the same using pandas:

days_in_year.py
import pandas as pd
def number_of_days_in_year(year):
    start = pd.Timestamp(year, 1, 1)
    end = pd.Timestamp(year + 1, 1, 1)
    return (end - start).days)

Usage example:

days_in_year_example.py
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:

pandas_timestamp_example.py
start = pd.Timestamp(year, 1, 1)

Now we generate the end date, which is the 1st of January of the following year:

pandas_end_timestamp.py
end = pd.Timestamp(year + 1, 1, 1)

The rest is simple: Just compute the difference (end - start) and ask pandas to give us the number of days:

pandas_days_diff.py
(end - start).days

 


Check out similar posts by category: Pandas, Python