0
0
PandasHow-ToBeginner · 3 min read

How to Extract Day from Datetime in pandas | Simple Guide

To extract the day from a datetime column in pandas, use the .dt.day attribute on a datetime Series. This returns the day of the month as an integer for each datetime value.
📐

Syntax

Use Series.dt.day to get the day of the month from a pandas datetime Series.

  • Series: A pandas Series with datetime values.
  • .dt: Accessor for datetime properties.
  • .day: Extracts the day as an integer (1 to 31).
python
df['date_column'].dt.day
💻

Example

This example shows how to create a pandas DataFrame with a datetime column and extract the day from it.

python
import pandas as pd

data = {'date_column': ['2024-06-01', '2024-06-15', '2024-06-30']}
df = pd.DataFrame(data)
df['date_column'] = pd.to_datetime(df['date_column'])
df['day'] = df['date_column'].dt.day
print(df)
Output
date_column day 0 2024-06-01 1 1 2024-06-15 15 2 2024-06-30 30
⚠️

Common Pitfalls

Common mistakes include:

  • Trying to use .day on a column that is not converted to datetime type, which causes an error.
  • Using .day on a string column without conversion.

Always convert your column to datetime first using pd.to_datetime().

python
import pandas as pd

data = {'date_column': ['2024-06-01', '2024-06-15', '2024-06-30']}
df = pd.DataFrame(data)

# Wrong: trying to extract day from string column
# df['day'] = df['date_column'].dt.day  # This will raise an error

# Right: convert to datetime first
df['date_column'] = pd.to_datetime(df['date_column'])
df['day'] = df['date_column'].dt.day
print(df)
Output
date_column day 0 2024-06-01 1 1 2024-06-15 15 2 2024-06-30 30
📊

Quick Reference

OperationCode ExampleDescription
Extract daydf['date_column'].dt.dayGets day of month as integer
Convert to datetimepd.to_datetime(df['date_column'])Converts string to datetime type
Extract monthdf['date_column'].dt.monthGets month as integer
Extract yeardf['date_column'].dt.yearGets year as integer

Key Takeaways

Use .dt.day on a datetime Series to get the day of the month.
Always convert your column to datetime type with pd.to_datetime() before extracting date parts.
Trying to use .dt.day on non-datetime columns causes errors.
The day extracted is an integer from 1 to 31 depending on the date.
You can similarly extract month and year using .dt.month and .dt.year.