0
0
Pandasdata~5 mins

Extracting year, month, day in Pandas

Choose your learning style9 modes available
Introduction

We extract year, month, and day from dates to understand and analyze time-based data easily.

When you want to group sales data by year or month to see trends.
When you need to filter records from a specific month or day.
When preparing data for time series analysis or visualization.
When calculating age or duration from birthdates or event dates.
When creating new features for machine learning models based on date parts.
Syntax
Pandas
df['date_column'].dt.year

df['date_column'].dt.month

df['date_column'].dt.day

Make sure the column is in datetime format before extracting parts.

Use pd.to_datetime() to convert strings to datetime if needed.

Examples
Adds a new column 'year' with the year extracted from 'date'.
Pandas
df['year'] = df['date'].dt.year
Adds a new column 'month' with the month number (1-12) extracted from 'date'.
Pandas
df['month'] = df['date'].dt.month
Adds a new column 'day' with the day of the month extracted from 'date'.
Pandas
df['day'] = df['date'].dt.day
Sample Program

This code creates a DataFrame with dates, converts them to datetime, then extracts year, month, and day into separate columns.

Pandas
import pandas as pd

# Sample data with dates as strings
data = {'date': ['2023-01-15', '2023-06-20', '2024-03-05']}
df = pd.DataFrame(data)

# Convert 'date' column to datetime type
df['date'] = pd.to_datetime(df['date'])

# Extract year, month, day into new columns
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day

print(df)
OutputSuccess
Important Notes

If the date column is not datetime, extraction will fail or give errors.

Use df['date'].dt.strftime('%Y-%m-%d') to format dates as strings if needed.

Summary

Convert your date column to datetime first.

Use .dt.year, .dt.month, and .dt.day to get parts.

These parts help analyze and organize time-based data easily.