Sub topic 8
Extracting date parts with .dt
This chapter assumes you can create a DataFrame and read a column by name. It also assumes you know how pd.to_datetime converts strings, which the previous chapters covered. Here you will use the .dt accessor to turn one datetime column into several feature columns.
What .dt does
The .dt accessor works on a Series with a datetime dtype (datetime64[ns]). It applies a datetime operation to every row and returns a Series with the same index. You can assign that Series to a new column, just like any other vectorized result.
Extracting parts
Convert first, then extract.
import pandas as pd
people = pd.DataFrame({
"name": ["Ann Lee", "Bob Ray", "Cy Fox"],
"joined": ["2026-01-15", "2026-02-03", "2026-02-28"],
})
people["joined"] = pd.to_datetime(people["joined"])
people["join_year"] = people["joined"].dt.year
people["join_month"] = people["joined"].dt.month
people["join_quarter"] = people["joined"].dt.quarter
people["join_weekday"] = people["joined"].dt.day_name()
print(people)The weekday values are Thursday, Tuesday, and Saturday. Attributes such as year, month, day, hour, quarter, and dayofweek have no parentheses. Methods such as day_name() and month_name() do. dayofweek counts Monday as 0.
Durations and rounding
Subtracting two datetime columns, or a column and a Timestamp, gives a timedelta Series. It has its own .dt attributes, such as days and total_seconds().
reference = pd.Timestamp("2026-03-01")
people["days_since_join"] = (reference - people["joined"]).dt.days
people["join_month_start"] = people["joined"].dt.to_period("M").dt.to_timestamp()
print(people[["name", "days_since_join", "join_month_start"]])The days_since_join values are 45, 26, and 1. Converting to a monthly period and back snaps each date to the first day of its month. That is a common key for grouping. For time-of-day rounding, use .dt.floor("h") or .dt.normalize(), which sets the time to midnight.
Common errors
- AttributeError: Can only use .dt accessor with datetimelike values. The column is still text (
objectdtype). Runpd.to_datetimefirst. - Floats instead of integers. Missing dates are
NaT(not a time)..dt.yearon a column containingNaTreturns floats withNaN, so2026becomes2026.0. Use.astype("Int64")if you need integers with gaps. - Wrong parse of ambiguous dates. A string like
03/04/2026can mean March 4 or April 3. Passformat="%d/%m/%Y"(ordayfirst=True) toto_datetimeinstead of relying on guessing. - Time zones.
.dtreads the local wall-clock time of a timezone-aware column. Convert with.dt.tz_convert(...)before extracting if you need a specific zone.
Exercise
Exercise
A column signup holds strings like "2026-05-17". You run df["signup"].dt.month and get an AttributeError. What is the cause, and what is the one-line fix that adds a signup_month column?
Show answer
The column has object (text) dtype, and .dt only works on datetime dtypes. Convert first, then extract: df["signup_month"] = pd.to_datetime(df["signup"]).dt.month.