pandas extract year from datetime code example

Example 1: extract year from datetime pandas

df['date'] = pd.to_datetime(df['date'],format='%Y%m%d')
df['year'] = pd.DatetimeIndex(df['date']).year
df['month'] = pd.DatetimeIndex(df['date']).month

Example 2: month from datetime pandas

#Exctract month and create a dedicated column df["Month"] from a 
#column in datetime format df["Date"]
df['Month'] = pd.DatetimeIndex(df['Date']).month

Example 3: to extract out only year month from a date column in pandas

df['month_year'] = df['date_column'].dt.to_period('M')

Example 4: python take the month of date in new column

#pandas datetimeindex docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html
df['month'] = pd.DatetimeIndex(df['birth_date']).month
df.head()