In this quick tutorial, we'll cover how we convert datetime to day of week or day name in Pandas.

There are two methods which can get day name of day of the week in Pandas:

(1) Get the name of the day from the week

df['date'].dt.day_name()

result:

0    Wednesday
1     Thursday

(2) Get the number of the day from the week

df['date'].dt.day_of_week

result:

0    2
1    3

Lets see a simple example which shows both ways.

Step 1: Create sample DataFrame with date

To start let's create a basic DataFrame with date column:

import pandas as pd

data = {'productivity': [80, 20, 60, 30, 50, 55, 95],
        'salary': [3500, 1500, 2000, 1000, 2000, 1500, 4000],
        'age': [25, 30, 40, 35, 20, 40, 22],
        'duedate': ["2020-10-14", "2020-10-15","2020-10-15", "2020-10-17","2020-10-14","2020-10-14","2020-10-18"],
        'person': ['Tim', 'Jim', 'Kim', 'Bim', 'Dim', 'Sim', 'Lim']
       }
df = pd.DataFrame(data)
df

result:

productivity salary age duedate person
80 3500 25 2020-10-14 Tim
20 1500 30 2020-10-15 Jim
60 2000 40 2020-10-15 Kim
30 1000 35 2020-10-17 Bim
50 2000 20 2020-10-14 Dim

If the date column is stored as a string we need to convert it to datetime by:

df['date'] = pd.to_datetime(df['duedate'])

You can learn more about datetime conversion in this article: How to Fix Pandas to_datetime: Wrong Date and Errors.

Step 2: Extract Day of week from DateTime in Pandas

To return day names from datetime in Pandas you can use method: day_name:

df['date'].dt.day_name()

Tde result is days of week for each date:

0    Wednesday
1     Thursday
2     Thursday
3     Saturday
4    Wednesday

Default language is english. It will return different languages depending on your locale.

Step 3: Extract Day number of week from DateTime in Pandas

If you need to get the day number of the week you can use the following:

  • day_of_week
  • dayofweek - alias
  • weekday - alias

This method counts days starting from Monday - which is presented by 0.

So for our DataFrame above we will have:

df['date'].dt.day_of_week

day numbers of the week is the output:

0    2
1    3
2    3
3    5
4    2

The final DataFrame will look like:

duedate person date day_name day_number
2020-10-14 Tim 2020-10-14 Wednesday 2
2020-10-15 Jim 2020-10-15 Thursday 3
2020-10-15 Kim 2020-10-15 Thursday 3
2020-10-17 Bim 2020-10-17 Saturday 5
2020-10-14 Dim 2020-10-14 Wednesday 2

Step 4: Get day name and number of week

If you need to get both of them and use it at the same time. For example to plot bar chart with the natural order of the days - Starting from Monday, Tuesday etc

df[['day_number', 'salary', 'day_name']].groupby(['day_number', 'day_name']).mean().sort_index().plot(kind='bar', legend=None)

For more information and detailed example you can check this article: Dates and Bar Plots (per weekday) in Pandas

Resources