You want to extract Month and Year from a Datetime column in Pandas.
Let’s read a dataset to work with.
import pandas as pd url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/tesla_stock_prices.csv' df = pd.read_csv(url) df.head()
Before you extract month and year from a column, you have to make sure that the data type of the column is datetime which you can do by using the info method.
We can see that the Date column is object type, so we have to first convert it to a datetime type. Let’s do that.
df['Date'] = pd.to_datetime(df['Date'])
We can see that the data type of the Date column is converted to datetime.
Now, to get the month and year from this column we will use –
df['Month'] = df['Date'].dt.month df['Year'] = df['Date'].dt.year
If you want Month and Year together then you have to write
df['Year Month'] = df['Date'].dt.to_period('M')