How to Extract Month Name and Year from Date column of DataFrame

Question:

I have the following DF

45    2018-01-01
73    2018-02-08
74    2018-02-08
75    2018-02-08
76    2018-02-08

I want to extract the month name and year in a simple way in the following format:

45    Jan-2018
73    Feb-2018
74    Feb-2018
75    Feb-2018
76    Feb-2018

I have used the df.Date.dt.to_period("M") which return "2018-01" format.

Asked By: syedmfk

||

Answers:

Cast you date from object to actual datetime and use dt to access what you need.

import pandas as pd

df = pd.DataFrame({'Date':['2019-01-01','2019-02-08']})

df['Date'] = pd.to_datetime(df['Date'])

# You can format your date as you wish
df['Mon_Year'] = df['Date'].dt.strftime('%b-%Y')

# the result is object/string unlike `.dt.to_period('M')` that retains datetime data type.

print(df['Mon_Year'])

Visual Format without affecting data types

We could also work with style to get the visual in the way we want without messing with underlying types


# note: returns a style object not df
df.style.format({"Date": lambda t: t.strftime("%b-%Y")})
Answered By: Prayson W. Daniel

First convert the column to datetime datatype using

sales_df['Date'] = pd.to_datetime(sales_df['Date'])

then you can do

sales_df['Month'] = sales_df['Date'].dt.month_name(locale='English')
Answered By: Naman Gala
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.