简体   繁体   English

Python - 如何以天为单位获得一年的确切长度?

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

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.所以我正在寻找一个替代方案, 文档没有提供一年的参数,它提供的最长时间长度是pd.Timedelta(1,'W')的一周,我无法得到确切的年份从那以后的几天。 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?那么,关于如何获得相同的 output 的任何建议?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM