pandas 从日期列中获取月份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51102615/
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
Get month from date column
提问by farzane
I need to extract the month from "datetime" column in my database and put it in a seperate column for each row. I tried code below and many others.
我需要从数据库中的“日期时间”列中提取月份,并将其放在每行的单独列中。我尝试了下面的代码和许多其他代码。
df3['DatumTijdOverlijden'] = pd.to_datetime(df3['DatumTijdOverlijden'],
format='"%Y-%m-%d %H:%M:%S"')
for x in df3['DatumTijdOverlijden']:
a = 'DatumTijdOverlijden'
datee = datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S)
df3.set_value(y, 'Month', datee)
y+=1
回答by jpp
You don't need a loop for this task. Just extract pd.Series.dt.month
attribute from your datetime
series. If you need your month as a string, you can use the pd.Series.dt.strtime
method. Here are some examples:
您不需要此任务的循环。只需pd.Series.dt.month
从您的datetime
系列中提取属性。如果您需要将月份作为字符串,则可以使用该pd.Series.dt.strtime
方法。这里有些例子:
df = pd.DataFrame({'Date': ['05-01-2018', '02-20-2020']})
df['Date'] = pd.to_datetime(df['Date'])
df['Month'] = df['Date'].dt.month
df['Month-str'] = df['Date'].dt.strftime('%b')
df['Month-str-full'] = df['Date'].dt.strftime('%B')
print(df)
Date Month Month-str Month-str-full
0 2018-05-01 5 May May
1 2020-02-20 2 Feb February