Sub topic 8
Extracting date parts with .dt
This chapter assumes you can build a DataFrame, select a column, and assign a new column. It also assumes you know what the previous chapters said about vectorized operations and pd.to_datetime. Here you will learn how the .dt accessor turns one datetime column into many derived columns, and where it quietly produces surprising results.
What the .dt accessor is
A datetime column stores each value as a timestamp, with year, month, hour and so on all packed together. The .dt accessor is a namespace on a Series that unpacks those components. Each attribute or method works on the whole column at once and returns a new Series with the same index. That makes it ready to assign as a column.
.dt only exists on columns whose dtype is datetime64, or on the related timedelta and period dtypes. A column of strings has dtype object and has no .dt. Convert first, then extract.
Setting up a datetime column
The examples below share one DataFrame. The last order has an unparseable date, which shows how missing values behave.
import pandas as pd
orders = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"ordered_at": ["2026-01-15 09:30", "2026-02-03 17:45",
"2026-02-28 23:10", "not a date"],
"shipped_at": ["2026-01-17", "2026-02-10", "2026-03-02", "2026-03-05"],
})
orders["ordered_at"] = pd.to_datetime(
orders["ordered_at"], format="%Y-%m-%d %H:%M", errors="coerce"
)
orders["shipped_at"] = pd.to_datetime(orders["shipped_at"])
print(orders.dtypes)Passing format= makes parsing faster and strict. It also avoids the ambiguity of 03/04/2026, which could mean March 4 or April 3. With errors="coerce", the bad string becomes NaT ("not a time"), the datetime version of NaN.
Pulling out components
Most parts are plain attributes, so there are no parentheses.
orders["year"] = orders["ordered_at"].dt.year
orders["month"] = orders["ordered_at"].dt.month
orders["weekday"] = orders["ordered_at"].dt.day_name()
orders["hour"] = orders["ordered_at"].dt.hour
orders["is_weekend"] = orders["ordered_at"].dt.dayofweek >= 5
print(orders[["order_id", "year", "month", "weekday", "hour", "is_weekend"]])Common attributes and methods:
| Accessor | Returns | Note |
|---|---|---|
| `.dt.year`, `.dt.month`, `.dt.day` | integers | Float if any value is `NaT` |
| `.dt.hour`, `.dt.minute`, `.dt.second` | integers | Same float behavior |
| `.dt.dayofweek` | 0 to 6 | Monday is 0, Sunday is 6 |
| `.dt.day_name()` | text | A method; takes an optional `locale` |
| `.dt.month_name()` | text | A method |
| `.dt.quarter` | 1 to 4 | Calendar quarter |
| `.dt.dayofyear` | 1 to 366 | |
| `.dt.is_month_end` | boolean | Also `is_month_start`, `is_quarter_end`, `is_year_end` |
| `.dt.isocalendar()` | DataFrame | Columns `year`, `week`, `day` |
day_name() and month_name() are methods, so they need parentheses. Forgetting them gives you a bound method object, not a column of names.
Whole-date operations
Sometimes you want a coarser timestamp, not a number. Three tools cover most cases:
orders["order_date"] = orders["ordered_at"].dt.normalize()
orders["order_hour"] = orders["ordered_at"].dt.floor("h")
orders["order_month"] = orders["ordered_at"].dt.to_period("M")
orders["iso_week"] = orders["ordered_at"].dt.isocalendar().week
print(orders[["order_date", "order_hour", "order_month", "iso_week"]])normalize()sets the time to midnight and keeps the datetime dtype. It is the usual way to get "the date" for grouping or merging.floor("h"),ceil()andround()snap timestamps to a frequency such as hours ("h"), 15 minutes ("15min") or days ("D").to_period("M")produces aPerioddtype that represents the whole month. It groups cleanly withgroupbyand prints as2026-01.
isocalendar() returns a DataFrame, so you select .week from it. The result has an unsigned nullable integer dtype and keeps the original index, so assignment lines up row by row.
Differences between dates
Subtracting two datetime columns gives a timedelta column. Its own .dt accessor exposes days, seconds and total_seconds().
gap = orders["shipped_at"] - orders["ordered_at"]
orders["days_to_ship"] = gap.dt.days
orders["days_to_ship_exact"] = gap.dt.total_seconds() / 86400
print(orders[["days_to_ship", "days_to_ship_exact"]]).dt.days is the whole-days component, not a rounded value. The first order is 1 day and 14.5 hours, so days reports 1 while the exact figure is about 1.60. Choose total_seconds() when partial days matter. Do not use .dt.seconds for total elapsed time. It returns only the seconds part left over after whole days are removed.
How missing dates flow through
NaT propagates. Every extraction on a NaT row gives a missing result, but the effect on the dtype depends on the attribute.
- Integer attributes such as
.dt.yearbecomefloat64, so 2026 shows as2026.0. Cast with.astype("Int64")(capital I) to keep whole numbers with a missing marker. .dt.day_name()givesNaNfor the row.- Comparisons built on a missing value return
False, not missing.
That last point is the trap. In the example above, dayofweek >= 5 is False for the bad row, so the row looks like a weekday order. If "unknown" must stay distinct, handle it explicitly:
weekend = orders["ordered_at"].dt.dayofweek >= 5
orders["is_weekend"] = weekend.where(orders["ordered_at"].notna())
orders["year"] = orders["ordered_at"].dt.year.astype("Int64")where keeps the value where the condition is true and inserts NaN elsewhere. The column becomes object dtype holding True, False and NaN. You can also use weekend.astype("boolean") after masking, to get the nullable boolean dtype.
Time zones
Parsed strings without an offset are "naive": they carry no time zone. Extracted parts reflect whatever the clock value says. If your data is really UTC and you want local hours, localize first and then convert.
local = (
orders["ordered_at"]
.dt.tz_localize("UTC")
.dt.tz_convert("America/New_York")
)
orders["local_hour"] = local.dt.hourtz_localize attaches a zone to naive values, and tz_convert shifts aware values to another zone. Calling tz_localize on values that already have a zone raises an error. Use tz_convert for those. Extract parts after conversion, because .dt.hour reports the hour in the column's current zone.
Common errors
The first error appears when the column is still text:
raw = pd.Series(["2026-01-15", "2026-02-03"])
try:
raw.dt.year
except AttributeError as err:
print(err)The message says .dt can only be used with datetimelike values. The fix is pd.to_datetime(raw) before extraction. A related problem is a column that looks like dates but converted partly. If one malformed value forces a mixed object result, check df.dtypes and inspect the failures with df[df["col"].isna()] after coercing.
Other mistakes to watch for:
- Assuming Sunday is 0. In pandas, Monday is 0.
- Using
.dt.week. It was removed. Use.dt.isocalendar().week. - Using uppercase
"H"infloor. Recent pandas versions deprecate it in favor of"h". - Expecting
.dt.dateto be fast or to keep the datetime dtype. It returns Pythondateobjects in anobjectcolumn. Prefernormalize()unless you need realdateobjects.
Exercise
Exercise
A DataFrame df has a text column signup with values like "2026-03-14 22:05" and one row containing "unknown". Write code that converts the column, adds a signup_quarter column as nullable integers, and adds is_month_end so that the "unknown" row is missing rather than False.
Show answer
df["signup"] = pd.todatetime(df["signup"], format="%Y-%m-%d %H:%M", errors="coerce") df["signupquarter"] = df["signup"].dt.quarter.astype("Int64") df["ismonthend"] = df["signup"].dt.ismonthend.where(df["signup"].notna()) The coerce option turns "unknown" into NaT. The quarter is float64 because of the missing value, so astype("Int64") restores whole numbers. ismonthend would be False for the NaT row, so where() replaces it with NaN.