简体   繁体   English

在 Pandas 中将原始日期转换为年/月/星期几

[英]Convert Raw Date into Year / Month / Day of Week in Pandas

I have a Pandas dataframe with raw dates formatted as such "19990130".我有一个 Pandas dataframe 原始日期格式为“19990130”。 I want to convert these into new columns: 'year', 'month', and 'dayofweek'.我想将这些转换为新列:“年”、“月”和“星期几”。

I tried using the following:我尝试使用以下内容:

pd.to_datetime(df['date'], format='%Y%m%d', errors='ignore').values

Which does give me an array of datetime objects.这确实给了我一组日期时间对象。 However, the next step I tried was using.to_pydatetime() and then.year to try to get the year out, like this:但是,我尝试的下一步是使用 .to_pydatetime() 和 then.year 来尝试结束这一年,如下所示:

pd.to_datetime(df['date'], format='%Y%m%d', errors='ignore').values.to_pydatetime().year

This works when I test a single value, but with a Pandas dataframe.这在我测试单个值时有效,但使用 Pandas dataframe。 I get:我得到:

'numpy.ndarray' object has no attribute 'to_pydatetime'

What's the easiest way to extract the year, month, and day of week from this data?从这些数据中提取年、月和星期几的最简单方法是什么?

Try:尝试:

s = pd.to_datetime(df['date'], format='%Y%m%d', errors='coerce')

s.dt.year
# or
# s.dt.month, etc

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

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