2

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?

Chris
  • 2,019
  • 5
  • 22
  • 67
  • Not all years have the same number of days. – DarkKnight Aug 24 '22 at 16:51
  • I know! But if you get one exact year, every year has the same number of days. As you can see, the result `365.2425` considers that every four years you add one day (which I guess It's the reason you are saying that not all years have the same number of days) – Chris Aug 24 '22 at 16:55
  • My point is that you cannot know how many days there are in a year unless you know what year it is – DarkKnight Aug 24 '22 at 16:56
  • Isn't that just a constant? – snwflk Aug 24 '22 at 17:27
  • What you're looking for is a constant. I agree it could be useful to have it incorporated in a module, the same way we can get pi from numpy. But you don't pretend numpy to _calculate_ pi every time you call it. Maybe they will incorporate it once they remove these units? – Ignatius Reilly Aug 24 '22 at 17:29
  • https://en.wikipedia.org/wiki/Year – snwflk Aug 24 '22 at 17:30
  • So even now, from a efficiency point of view, it would be better just to do `days_in_year = 365.2425` – Ignatius Reilly Aug 24 '22 at 17:31

1 Answers1

0

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)
snwflk
  • 3,341
  • 4
  • 25
  • 37