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
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With