Extracting month/Year from a date column in Pandas DataFrame

This is a common requirement when dealing with dates in data in Machine Learning. You may want to extract specific parts of dates like Month, Year, Quarter, etc to generate new features for Machine Learning.

The function used to extract values from Dates is strftime() if the date format is datetime.

Below snippet extracts the Month, Year, Day in different formats from a given date.

Sample Output:

Extracting Month/Year/Day from a date in Python
Extracting Month/Year/Day from a date in Python


The datetime function does not have a built-in function to extract quarter. Hence the function Timestamp() from pandas library comes in picture! The Timestamp date object has built-in attributes like quarter, week, month to get the relevant information.

Below code converts the datetime date into pandas Timestamp date and then extracts quarter, month, week, etc. from it

Sample Output:

Extracting Quater/week/month from a pandas Timestamp date
Extracting Quater/week/month from a pandas Timestamp date


How to extract month/year for a whole column?

If you need to extract the month/year/week/quarter for the whole date column in your dataframe, then it will involve creating a custom function to get the required items from a date and apply that function to every row using the apply() function.

Sample Output:

Extracting Month/Year for the whole column in a pandas dataframe
Extracting Month/Year for the whole column in a pandas dataframe

Author Details
Lead Data Scientist
Farukh is an innovator in solving industry problems using Artificial intelligence. His expertise is backed with 10 years of industry experience. Being a senior data scientist he is responsible for designing the AI/ML solution to provide maximum gains for the clients. As a thought leader, his focus is on solving the key business problems of the CPG Industry. He has worked across different domains like Telecom, Insurance, and Logistics. He has worked with global tech leaders including Infosys, IBM, and Persistent systems. His passion to teach inspired him to create this website!

Leave a Reply!

Your email address will not be published. Required fields are marked *