Python - How to get the exact length of one year in days?

Viewed 66

As I'm working with time series, I'm needing the exact number of days in one year. Currently, I do this:

import pandas as pd

pd.Timedelta("1Y") / pd.Timedelta("1D")

365.2425 # Output

Which works! But it comes with a warning:

FutureWarning: Units 'M', 'Y' and 'y' do not represent unambiguous timedelta values and will be removed in a future version.

So I'm looking for an alternative, the documentation doesn't provide an argument for a year and the longest time length it offers is a week with pd.Timedelta(1,'W') and I can't get an exact year in days from that. Also, The only question similar to mine I found was this one which has the same warning but for a very different issue and I don't see a way to a solution from its answer.

So, any suggestion on how could I get the same output with an alternative?

1 Answers

It seems you're looking for the average number of days in a year of the Gregorian calendar.

Which is a constant:

def get_days_in_avg_year():
  return 365.2425

You can also prove this to yourself by following the rules:

num_years = 400
num_leap_years = len([x for x in range(num_years) if x % 4 == 0 and not (x % 100 == 0 and x % 400 != 0)])
num_days = num_years*365 + num_leap_years
print(num_days / num_years)
Related