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

14,780

Solution 1

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'])

Solution 2

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')
Share:
14,780
syedmfk
Author by

syedmfk

Updated on June 19, 2022

Comments

  • syedmfk
    syedmfk almost 2 years

    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.

  • snapcrack
    snapcrack almost 5 years
    I don't think you need the dt before year and the column?
  • Prayson W. Daniel
    Prayson W. Daniel almost 5 years
    I believe you do. After casting df['Date].dt.year` shows year. You have all datetime functions as month, day, week number etc from dt
  • syedmfk
    syedmfk almost 5 years
    I am getting the value i wanted. However, since its returning string value, sorting the Date [for plotting and other use] has become an issue.
  • Prayson W. Daniel
    Prayson W. Daniel almost 5 years
    Yes, that is why .dt.to_period is used. What tools are you using to plot?
  • syedmfk
    syedmfk almost 5 years
    i am using "seaborn"
  • Prayson W. Daniel
    Prayson W. Daniel almost 5 years
    Try: df.set_index('Date') and the plot whatever columns with df['My_Numeric_Col'].plot(linewidth=0.5) see dataquest.io/blog/tutorial-time-series-analysis-with-pandas
  • Carmoreno
    Carmoreno almost 3 years
    Please, formatting your code to improve legibility. (Using Ctrl. + K)