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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import datetime # Creating today's date Today=datetime.datetime.now() print(Today) print('Month:',Today.strftime('%b')) print('Full Month:', Today.strftime('%B')) print('Numeric Month',Today.strftime('%m')) print('Day:', Today.strftime('%d')) print('Year(YY):',Today.strftime('%y')) print('Year(YYYY):',Today.strftime('%Y')) |
Sample Output:

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
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import datetime Today=datetime.datetime.now() print(Today) # Using Pandas Timestamp to get quarter TodayTimeStamp=pd.Timestamp(Today) print(TodayTimeStamp) print('Quarter:',TodayTimeStamp.quarter) print('Month:',TodayTimeStamp.month) print('Month:',TodayTimeStamp.year) print('Day:',TodayTimeStamp.day) print('Week of Year:',TodayTimeStamp.week) |
Sample Output:

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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# Defining Department Data import pandas as pd DepartmentData=pd.DataFrame({'Dep': ['BI','QA','DEV'], 'id': [101,102,103], 'DOJ': ['12-Mar-2020','2-Feb-2020','15-Jan-2020'] }) # Priting data print(DepartmentData) # Defining a Function to convert a string to date def CreateDate(InpString): import datetime return(datetime.datetime.strptime(InpString, '%d-%b-%Y')) # Creating the Joining Date DepartmentData['JoiningDate']=DepartmentData['DOJ'].apply(CreateDate) print(DepartmentData) # Defining a function to get month def getMonth(DOJ): return(DOJ.strftime('%B')) # Defining a function to get year def getYear(DOJ): return(DOJ.strftime('%Y')) # Applying the month and year extractor functions DepartmentData['JoiningMonth']=DepartmentData['JoiningDate'].apply(getMonth) DepartmentData['JoiningYear']=DepartmentData['JoiningDate'].apply(getYear) print(DepartmentData) |
Sample Output:

