Sub topic 4
Extracting year, month, weekday, and more with .dt
This chapter assumes you can build a DataFrame, select columns, and have already converted a column to datetime64 with pd.to_datetime. Here you will pull calendar parts out of that column and use them for grouping and filtering.
The .dt accessor
A datetime64 column has a .dt accessor. It works like .str for strings. You call series.dt.<name> and pandas applies the operation to every element at once. It returns a new Series with the same index.
Extracting components
import pandas as pd
df = pd.DataFrame({
"when": pd.to_datetime(
["2024-03-01 09:30", "2024-03-02 14:45", "2024-03-05 08:00"]
),
"amount": [10, 25, 40],
})
df["weekday"] = df["when"].dt.day_name()
df["month"] = df["when"].dt.month
df["gap"] = df["when"].diff()
df["gap_hours"] = df["gap"].dt.total_seconds() / 3600
print(df)The first row has NaT in gap, because it has no earlier row to subtract. The other gaps are 29.25 and 65.25 hours.
The gap column holds Timedelta values, and it has its own .dt accessor. That is why .dt.total_seconds() works on it.
Common attributes:
| Attribute | Returns | Notes |
|---|---|---|
| `.dt.year`, `.dt.month`, `.dt.day` | integers | Month runs 1 to 12. |
| `.dt.hour`, `.dt.minute` | integers | 24-hour clock. |
| `.dt.dayofweek` | integer | Monday is 0, Sunday is 6. |
| `.dt.day_name()` | text | A method, so it needs parentheses. |
| `.dt.quarter` | integer | 1 to 4. |
| `.dt.isocalendar()` | DataFrame | Columns `year`, `week`, `day`. |
Flags, truncation, and rounding
Components are useful for building filters and group keys. Rounding methods keep a full timestamp but drop precision.
df["year"] = df["when"].dt.year
df["dow"] = df["when"].dt.dayofweek
df["is_weekend"] = df["dow"] >= 5
df["day"] = df["when"].dt.normalize()
df["hour_start"] = df["when"].dt.floor("60min")
print(df[["when", "year", "dow", "is_weekend", "day", "hour_start"]])This block continues from the previous one and reuses df. normalize() sets the time to midnight and keeps the datetime64 dtype. floor(), ceil(), and round() take a frequency string.
Grouping by a component is a common use:
print(df.groupby(df["when"].dt.month)["amount"].sum())Common errors
- AttributeError: Can only use .dt accessor with datetimelike values. The column is still text (
objectdtype). Checkdf.dtypes, then convert withpd.to_datetime. - Missing values turn integers into floats. If a column contains
NaT,.dt.monthreturns floats such as3.0, withNaNwhere the time was missing. Drop or fill theNaTrows first. You can also convert the result with.astype("Int64"). - Forgetting parentheses.
.dt.yearis an attribute..dt.day_name()and.dt.normalize()are methods. - Off-by-one weekdays.
dayofweekstarts at Monday = 0, not Sunday. Weekend means 5 and 6. - Using
.dton the index. ADatetimeIndexexposes the same names directly, such asts.index.month, with no.dt.
Exercise
A DataFrame df has a datetime64 column when. Write one expression that keeps only the rows that fall on a Saturday or Sunday. What would you check first if it raised an AttributeError mentioning .dt?
Show answer
Use df[df["when"].dt.dayofweek >= 5]. Monday is 0, so 5 is Saturday and 6 is Sunday. An AttributeError about .dt means the column is not a datetime dtype. Check df.dtypes and convert with pd.to_datetime(df["when"]).