从日期列获取月份

时间:2018-06-29 13:13:55

标签: python database pandas datetime

我需要从数据库的“ datateime”列中提取月份,并将其放在每一行的单独列中。我尝试了下面的代码以及许多其他代码。你能帮我吗!

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

1 个答案:

答案 0 :(得分:1)

此任务不需要循环。只需从您的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