0
0
Pandasdata~5 mins

dt accessor for datetime properties in Pandas

Choose your learning style9 modes available
Introduction

The dt accessor helps you easily get parts of dates and times from your data. It makes working with dates simple and clear.

You want to find the year or month from a list of dates.
You need to filter data by day of the week, like only Mondays.
You want to add a new column showing the hour from timestamps.
You need to check if dates fall on weekends.
You want to extract the day or week number from dates.
Syntax
Pandas
dataframe['date_column'].dt.property

date_column must be a datetime type for dt to work.

Common properties include year, month, day, hour, weekday, and more.

Examples
Gets the year from each date in the date column.
Pandas
df['date'].dt.year
Extracts the month number from each date.
Pandas
df['date'].dt.month
Returns the day of the week as a number (Monday=0, Sunday=6).
Pandas
df['date'].dt.weekday
Gets the hour from datetime values that include time.
Pandas
df['date'].dt.hour
Sample Program

This code creates a table with dates and extracts different parts like year, month, day, weekday number, and hour into new columns.

Pandas
import pandas as pd

data = {'date': ['2023-01-15 08:30:00', '2023-06-20 14:45:00', '2023-12-25 00:00:00']}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])

# Extract year, month, day, weekday, and hour
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
df['weekday'] = df['date'].dt.weekday
df['hour'] = df['date'].dt.hour

print(df)
OutputSuccess
Important Notes

If your date column is not datetime type, use pd.to_datetime() to convert it first.

The weekday property counts Monday as 0 and Sunday as 6.

You can also use dt.day_name() to get the weekday name as text.

Summary

The dt accessor lets you get parts of dates easily.

Use it to extract year, month, day, hour, weekday, and more.

Make sure your data is in datetime format before using dt.