0
0
Pandasdata~5 mins

Extracting day of week and hour in Pandas

Choose your learning style9 modes available
Introduction

We extract the day of the week and hour from dates to understand when events happen. This helps us find patterns in time-based data.

You want to see which days of the week have the most sales.
You need to analyze what hours of the day users visit a website.
You want to group data by weekday or hour to find trends.
You are working with timestamps and want to simplify them to day or hour.
You want to create charts showing activity by day or hour.
Syntax
Pandas
df['day_of_week'] = df['date_column'].dt.dayofweek
# Monday=0, Sunday=6

df['hour'] = df['date_column'].dt.hour

Use .dt.dayofweek to get the day number (Monday=0 to Sunday=6).

Use .dt.hour to get the hour from a datetime column.

Examples
This adds a new column with numbers 0-6 for the day of the week.
Pandas
df['day_of_week'] = df['timestamp'].dt.dayofweek
This adds a new column with the hour (0-23) from the timestamp.
Pandas
df['hour'] = df['timestamp'].dt.hour
This adds a column with the full weekday name like 'Monday'.
Pandas
df['weekday_name'] = df['timestamp'].dt.day_name()
Sample Program

This code creates a small table with timestamps, converts them to datetime, then extracts the day of week and hour into new columns.

Pandas
import pandas as pd

data = {'timestamp': ['2024-06-01 08:30:00', '2024-06-02 15:45:00', '2024-06-03 23:10:00']}
df = pd.DataFrame(data)
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['day_of_week'] = df['timestamp'].dt.dayofweek
df['hour'] = df['timestamp'].dt.hour
print(df)
OutputSuccess
Important Notes

Remember Monday is 0 and Sunday is 6 when using dayofweek.

You can also get the weekday name with dt.day_name() if you want words instead of numbers.

Make sure your column is in datetime format before extracting day or hour.

Summary

Extract day of week using .dt.dayofweek for numbers 0-6.

Extract hour using .dt.hour for hours 0-23.

Convert your column to datetime first with pd.to_datetime().