To extract the day of the week from a datetime column in pandas, you can access the “dayofweek” property. The “dayofweek” property returns a 64-bit integer between 0 and 6, where 0 represents Monday and 6 represents Sunday.

import pandas as pd

df = pd.DataFrame({
    "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"],
    "sales": [100,30,50,60,10,80]
})

df["date"] = pd.to_datetime(df["date"])

df["dayofweek"] = df["date"].dt.dayofweek

print(df)

#Output:
        date  sales  dayofweek
0 2021-09-30    100          3
1 2021-12-31     30          4
2 2022-03-31     50          3
3 2022-06-30     60          3
4 2022-09-30     10          4
5 2022-12-31     80          5

When working with data which contains information over time, the ability to extract certain pieces of information from our data easily is valuable.

One such piece of information is getting the day of the week from a date when using pandas in Python.

To get the day of the week from a datetime column in pandas, you can access the pandas datetime “dayofweek” property.

The “dayofweek” property returns a 64-bit integer between 0 and 6, where 0 represents Monday and 6 represents Sunday.

Below is a simple example which shows you how to get the day of the week from a datetime columns in a pandas DataFrame.

import pandas as pd

df = pd.DataFrame({
    "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"],
    "sales": [100,30,50,60,10,80]
})

df["date"] = pd.to_datetime(df["date"])

df["dayofweek"] = df["date"].dt.dayofweek

print(df)

#Output:
        date  sales  dayofweek
0 2021-09-30    100          3
1 2021-12-31     30          4
2 2022-03-31     50          3
3 2022-06-30     60          3
4 2022-09-30     10          4
5 2022-12-31     80          5

Get Day Name from Datetime in pandas

If you want to get the name of weekday from a datetime, instead of just the day of the week number, then you can use pandas datetime day_name() function.

The day_name() function returns the name of the weekday.

Below is the same DataFrame as above but now we will get the day names for each datetime in the date column.

import pandas as pd

df = pd.DataFrame({
    "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"],
    "sales": [100,30,50,60,10,80]
})

df["date"] = pd.to_datetime(df["date"])

df["day_name"] = df["date"].dt.day_name()

print(df)

#Output:
        date  sales  day_name
0 2021-09-30    100  Thursday
1 2021-12-31     30    Friday
2 2022-03-31     50  Thursday
3 2022-06-30     60  Thursday
4 2022-09-30     10    Friday
5 2022-12-31     80  Saturday

Hopefully this article has been useful for you to learn how to get the day of the week from a datetime variable in a pandas DataFrame in Python.

Categorized in:

Python,

Last Update: March 1, 2024