如何使用 Pandas 根据实际日期查找一年中的天数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27239063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the number of the day in a year based on the actual dates using Pandas?
提问by finstats
My data frame datahas a date variable dateOpenwith the following format date_format = "%Y-%m-%d %H:%M:%S.%f"and I would like to have a new column called openDaywhich is the day number based on 365 days a year. I tried applying the following
我的数据框data有一个dateOpen具有以下格式的日期变量,date_format = "%Y-%m-%d %H:%M:%S.%f"我想要一个名为的新列openDay,它是基于一年 365 天的天数。我尝试应用以下
data['dateOpen'] = [datetime.strptime(dt, date_format) for dt in data['dateOpen']]
data['openDay'] = [dt.day for dt in data['dateOpen']]
however, I get the day in the month. For example if the date was 2013-02-21 10:12:14.3then the above formula would return 21. However, I want it to return 52 which is 31 days from January plus the 21 days from February.
然而,我得到了这个月的一天。例如,如果日期是2013-02-21 10:12:14.3那么上面的公式将返回 21。但是,我希望它返回 52,即从一月开始的 31 天加上从二月开始的 21 天。
Is there a simple way to do this in Pandas?
在 Pandas 中是否有一种简单的方法可以做到这一点?
回答by behzad.nouri
On latestpandas you can use date-time properties:
在最新的Pandas上,您可以使用日期时间属性:
>>> ts = pd.Series(pd.to_datetime(['2013-02-21 10:12:14.3']))
>>> ts
0 2013-02-21 10:12:14.300000
dtype: datetime64[ns]
>>> ts.dt.dayofyear
0 52
dtype: int64
On older versions, you maybe able to convert to a DatetimeIndexand then use .dayofyearproperty:
在旧版本上,您可以转换为 aDatetimeIndex然后使用.dayofyear属性:
>>> pd.Index(ts).dayofyear # may work
array([52], dtype=int32)
回答by Jon Clements
Not sure if there's a pandasbuiltin, but in Python, you can get the "Julian" day, eg:
不确定是否有pandas内置函数,但在 Python 中,您可以获得“Julian”日,例如:
data['openDay'] = [int(format(dt, '%j')) for dt in data['dateOpen']]
Example:
例子:
>>> from datetime import datetime
>>> int(format(datetime(2013,2,21), '%j'))
52
回答by Koloth
#To find number of days in this year sofar
from datetime import datetime
from datetime import date
today = date.today()
print("Today's date:", today)
print(int(format(today, '%j')))
Today's date: 2020-03-26
86
今日日期:2020-03-26
86

