简体   繁体   English

如何从 python 中的日期中提取年份和月份

[英]How to extract year and month from date in python

I tried some functions but those functions cannot produce the right answer for some dates enter image description here .我尝试了一些功能,但这些功能无法为某些日期生成正确的答案,请在此处输入图像描述 Like the first date "12/11/2015", the month should be 11 instead of 12. Anyone knows how to solve this in general?就像第一个日期“12/11/2015”一样,月份应该是 11 而不是 12。任何人都知道一般如何解决这个问题?

You just have to add another argument called dayfirst: bool , like so:您只需添加另一个名为dayfirst: bool的参数,如下所示:

import pandas as pd

df = pd.DataFrame({
    'date': ['12/11/2015', '19/11/2015', '7/12/2015']
})

df['month'] = pd.DatetimeIndex(df['date'], dayfirst=True).month
df['year'] = pd.DatetimeIndex(df['date'], dayfirst=True).year
print(df)

Result:结果:

         date  month  year
0  12/11/2015     11  2015
1  19/11/2015     11  2015
2   7/12/2015     12  2015

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

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