简体   繁体   English

如何从日期列中提取年、月、日?

[英]How to extract year, month, date from a date column?

I'm trying to extract date information from a date column, and append the new columns to the original dataframe .我正在尝试从日期列中提取日期信息,并将 append 新列添加到原始dataframe中。 However, I kept getting this message saying I cannot use .dt with this column.但是,我不断收到此消息,说我不能在此列中使用.dt Not sure what I did wrong here, any help will be appreciated.不知道我在这里做错了什么,任何帮助将不胜感激。

Error message that I got in python:我在 python 中收到的错误消息:

我在 python 中收到的错误消息

First do df.datecolumn = pd.to_datetime(df.datecolumn) , then live happily ever after.先做df.datecolumn = pd.to_datetime(df.datecolumn) ,然后过上幸福的生活。

This will give you year, month and day in that month.这将为您提供该月的年、月和日。 You can also easily get week of the year and day of the week.您还可以轻松获取一年中的一周和一周中的一天。

import pandas as pd

df = pd.DataFrame(data=[['1920-01-01'], ['2008-12-06']], columns=['Date'])

df['Date'] = pd.to_datetime(df['Date'])

df['Year'] = df['Date'].apply(lambda x : x.year)
df['Month'] = df['Date'].apply(lambda x : x.month)
df['Day'] = df['Date'].apply(lambda x : x.day)

print(df)

In your Time list you have a typo Dayorweek should be dayofweek .在您的Time列表中,您有一个错字Dayorweek应该是dayofweek

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

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