In this short tutorial we’ll show how to use Python to easily convert a Pandas DataFrame datetime column and get instead the name of the weekday.
Create an example DataFrame
Let’s assume the following DataFrame:
import pandas as pd
#Define Data
office = ['Denver','Paris', 'Denver', 'London' ]
full_date = ['1-15-2022 13:45:00', '4-8-2022 08:45:00', '2-23-2022 12:45:00', '4-7-2022 13:46:00']
salary = [143, 153, 128, 149]
hiring_dict = dict( office=office,hire_date=full_date,salary = salary)
# Create DataFrame
hiring_df = pd.DataFrame(data=hiring_dict)
Let’s look at the Data types of the DataFrame:
hiring_df.dtypes
Here’s the result we’ll get. It looks like we should first cast the hire_date column to datetime64 first.
office object hire_date object salary int64 dtype: object
Convert datetime to day of week
If we’ll try to convert the hire_date column to day of the week we’ll receive an error.
hiring_df['hire_date'].dt.weekday
Pandas will throw the following message:
AttributeError: Can only use .dt accessor with datetimelike values
As mentioned above, before proceeding we first need to ensure our column data type is datetime. We can then use the dt accessor to find date values. Initially we’ll find the value of the day of the week of each observation in our data:
hiring_df['hire_weekday'] = \
pd.to_datetime(hiring_df['hire_date']).dt.weekday
Alternatively, we can use the following:
hiring_df['hire_weekday'] = \ pd.to_datetime(hiring_df['hire_date']).dt.day_of_week
One more option is to use the astype method:
hiring_df['hire_weekday']= \
(hiring_df['hire_date']).astype('datetime64').dt.day_of_week
All the above will render the weekday number as shown below:
hiring_df.head()
office | hire_date | salary | hire_weekday | |
---|---|---|---|---|
0 | Denver | 1-15-2022 13:45:00 | 143 | 5 |
1 | Paris | 4-8-2022 08:45:00 | 153 | 4 |
2 | Denver | 2-23-2022 12:45:00 | 128 | 2 |
3 | London | 4-7-2022 13:46:00 | 149 | 3 |
Find the day of week name
In a similar fashion we can use the dt.day_name() function to retrieve the name of the week day.
hiring_df['hire_day_name'] = \
pd.to_datetime(hiring_df['hire_date']).dt.day_name()
Create a column with month names
As we have seen above,we ca use the dt accessor in order to extract several date/time values. In a similar fashion, we’ll now go ahead and extract the month name into a new DataFrame column:
hiring_df['hire_month'] = \ pd.to_datetime(hiring_df['hire_date']).dt.month_name()
And here are our complete DataFrame values:
office | hire_date | salary | hire_weekday | hire_day_name | hire_month | |
---|---|---|---|---|---|---|
0 | Denver | 1-15-2022 13:45:00 | 143 | 5 | Saturday | January |
1 | Paris | 4-8-2022 08:45:00 | 153 | 4 | Friday | April |
2 | Denver | 2-23-2022 12:45:00 | 128 | 2 | Wednesday | February |
3 | London | 4-7-2022 13:46:00 | 149 | 3 | Thursday | April |