4

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
jpp
  • 159,742
  • 34
  • 281
  • 339
farzane
  • 41
  • 1
  • 1
  • 5
  • related: https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-from-pandas-datetime-column-python – EdChum Jun 29 '18 at 13:16

1 Answers1

18

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
jpp
  • 159,742
  • 34
  • 281
  • 339