简体   繁体   English

如何从熊猫数据框中提取日期/年/月?

[英]How do I extract the date/year/month from pandas dataframe?

I'm trying to extract year/date/month info from the 'date' column in pandas dataframe. 我正在尝试从pandas数据框中的“日期”列中提取年/日期/月信息。 Here is my sample code: 这是我的示例代码:

from datetime import datetime
def date_split(calendar):
  for row in calendar: 
    new_calendar={}
    listdate=datetime.strptime(row['date'],'%Y-%M-%D')

I haven't finished the complete code, but when i test run this part I keep getting error like this: 我还没有完成完整的代码,但是当我测试运行此部分时,我总是收到如下错误:

----> 7         listdate=datetime.strptime(row['date'],'%Y-%M-%D')
TypeError: string indices must be integers

Anyone has any idea? 有人知道吗?

Btw, this is the dataframe I use (calendar_data): 顺便说一句,这是我使用的数据框(calendar_data):

在此处输入图片说明

It seems you need to_datetime : 看来您需要to_datetime

print (df['date'].dtype)
object

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

print (df['date'].dtype)
datetime64[ns]

If need extract year , month and day to new columns: 如果需要将yearmonthday提取到新列中:

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day

If need list of date s: 如果需要date list

listdate = df['date'].dt.date.tolist()
print (listdate)

[datetime.date(2017, 9, 5), 
 datetime.date(2017, 9, 4),
 datetime.date(2017, 9, 3), 
 datetime.date(2017, 9, 2),
 datetime.date(2017, 9, 1)]

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

相关问题 如何从DataFrame的日期列中提取月份名称和年份 - How to Extract Month Name and Year from Date column of DataFrame 如何一次从 dataframe 的多个日期列中提取年份和月份? (得到一个错误) - How can i extract the year and month from multiple date columns in a dataframe at once? (getting an error) 如何用日期(年/月)绘制pandas DataFrame? - How to plot pandas DataFrame with date (Year/Month)? 如何有效地从 Pandas 的数据帧头中提取日期年份? - How to efficiently extract date year from dataframe header in Pandas? 从熊猫数据框中的“年-月-日”格式中删除年份 - Drop the year from "Year-month-date" format in a pandas dataframe 如何从 dataframe 中的字符串中提取年份和月份 - How to extract year and month from string in a dataframe 如何从 python 中的日期中提取年份和月份 - How to extract year and month from date in python 如何在熊猫数据框中将日期类型从“year_week”更改为“day_month_year”格式? - How to change date type from 'year_week' to 'day_month_year' format in pandas dataframe? 如何使用 Pandas dataframe 从 4 月开始计算财政年度的年初至今(YTD)? - How to calculate year to date (YTD) of a financial year starting from month April using Pandas dataframe? 如何从DateField对象中提取日,月,年? - How do I extract day,month,year from a DateField object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM