从python中的日期中提取月份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26105804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:05:42 来源:igfitidea点击:
extract month from date in python
提问by dana111
I have a column of dates in the format 2010-01-31. I can extract the year using
我有一列日期格式为 2010-01-31。我可以使用提取年份
#extracting year
year = df["date"].values
year = [my_str.split("-")[0] for my_str in year]
df["year"] = year
I'm trying to get the month, but I don't understand how to get it on the second split.
我试图得到这个月,但我不明白如何在第二次分裂中得到它。
回答by g4ur4v
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
回答by Abdelouahab
import datetime
a = '2010-01-31'
datee = datetime.datetime.strptime(a, "%Y-%m-%d")
datee.month
Out[9]: 1
datee.year
Out[10]: 2010
datee.day
Out[11]: 31

