[英]How to find the number of the day in a year based on the actual dates using Pandas?
My data frame data
has a date variable dateOpen
with the following format date_format = "%Y-%m-%d %H:%M:%S.%f"
and I would like to have a new column called openDay
which is the day number based on 365 days a year.我的数据框data
有一个日期变量dateOpen
,格式如下date_format = "%Y-%m-%d %H:%M:%S.%f"
我想要一个名为openDay
的新列,它是基于一年 365 天的天数。 I tried applying the following我尝试应用以下
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.3
then 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 中是否有一种简单的方法可以做到这一点?
On latest pandas you can use date-time properties :在最新的熊猫上,您可以使用日期时间属性:
>>> 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 may be able to convert to a DatetimeIndex
and then use .dayofyear
property:在旧版本上,您可以转换为DatetimeIndex
,然后使用.dayofyear
属性:
>>> pd.Index(ts).dayofyear # may work
array([52], dtype=int32)
Not sure if there's a pandas
builtin, but in Python, you can get the "Julian" day, eg:不确定是否有内置的pandas
,但在 Python 中,您可以获得“朱利安”日,例如:
data['openDay'] = [int(format(dt, '%j')) for dt in data['dateOpen']]
Example:例子:
>>> from datetime import datetime
>>> int(format(datetime(2013,2,21), '%j'))
52
#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今日日期:2020-03-26
86 86
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.