Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get month from date column

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
like image 633
farzane Avatar asked Dec 02 '22 11:12

farzane


1 Answers

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
like image 140
jpp Avatar answered Dec 14 '22 23:12

jpp