Sub topic 4
Extracting year, month, weekday, and more with .dt
This chapter assumes you can build a pandas Series or DataFrame, select columns, and filter rows with boolean masks. It also assumes you already have a column of real datetime values, as produced by pd.to_datetime in the parsing chapter. Here you will pull calendar pieces out of those values and use them for grouping, filtering, and labeling.
What the .dt accessor is
The .dt accessor exposes datetime properties and methods on a Series whose dtype is datetime64. It works on the whole column at once, so you never loop over rows or call Python's datetime methods one value at a time.
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",
"2024-12-31 23:59",
]),
"amount": [10, 25, 40, 5],
})
df["year"] = df["when"].dt.year
df["month"] = df["when"].dt.month
df["day"] = df["when"].dt.day
df["hour"] = df["when"].dt.hour
df["weekday_num"] = df["when"].dt.dayofweek
df["weekday"] = df["when"].dt.day_name()
print(df)Each new column is a Series aligned with the original index. The numeric ones are integers. day_name() returns strings such as Friday.
The accessor needs a datetime dtype
If the column still holds strings, .dt fails. This is the most common error with the accessor.
import pandas as pd
raw = pd.Series(["2024-01-01", "2024-01-02"])
try:
raw.dt.year
except AttributeError as err:
print(err)
print(pd.to_datetime(raw).dt.year.tolist())The error message is Can only use .dt accessor with datetimelike values. Check df.dtypes first. If the dtype is object or string, convert it with pd.to_datetime, then use .dt.
Common components
The properties below cover most day-to-day work. All of them return a Series with the same index as the source.
| Property or method | Returns | Notes |
|---|---|---|
| `dt.year`, `dt.month`, `dt.day` | integers | `month` runs 1 to 12 |
| `dt.hour`, `dt.minute`, `dt.second` | integers | 24-hour clock |
| `dt.dayofweek` (alias `dt.weekday`) | integers 0 to 6 | Monday is 0, Sunday is 6 |
| `dt.dayofyear` | integers 1 to 366 | Day number within the year |
| `dt.quarter` | integers 1 to 4 | Calendar quarters |
| `dt.days_in_month` | integers 28 to 31 | Length of that row's month |
| `dt.day_name()`, `dt.month_name()` | strings | Accept a `locale=` argument |
| `dt.is_month_start`, `dt.is_month_end` | booleans | Also `is_quarter_*` and `is_year_*` |
| `dt.is_leap_year` | booleans |
Note that day_name() and month_name() are methods, so they need parentheses. The numeric properties are attributes and do not. Writing dt.day_name without parentheses gives you a bound method, not a column.
Weekday numbers: Monday is 0
Python's datetime.weekday() and pandas' dayofweek agree: Monday is 0. This differs from some databases and from Excel, where Sunday can be 1 or 0. When you compare results with another system, check the convention first.
A weekend flag then reads naturally:
df["is_weekend"] = df["when"].dt.dayofweek >= 5
print(df[["when", "weekday", "is_weekend"]])Using components to filter and group
Components are most useful as masks and grouping keys. Once a component is a Series, it works like any other column.
march = df[df["when"].dt.month == 3]
print(march["amount"].sum())
order = ["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"]
by_day = (
df.groupby(df["when"].dt.day_name())["amount"]
.sum()
.reindex(order, fill_value=0)
)
print(by_day)groupby sorts the group keys alphabetically, so Friday would come first. Calling reindex with an explicit list restores calendar order. The fill_value=0 argument keeps weekdays that have no data as zeros instead of NaN.
You can pass the .dt result directly to groupby without storing it as a column. The Series shares the DataFrame's index, so pandas aligns the keys with the rows.
Grouping by month needs the year too
Grouping on dt.month alone merges March 2024 with March 2023 and every other March in the data. If your data spans more than one year, group by both parts:
by_year_month = df.groupby(
[df["when"].dt.year, df["when"].dt.month]
)["amount"].sum()
print(by_year_month)A shorter route is df["when"].dt.to_period("M"), which gives one label per calendar month such as 2024-03. The periods chapter covers that type in detail.
Rounding: floor, ceil, round, and normalize
The .dt accessor also has methods that return timestamps instead of integers. They snap values to a regular grid, which is helpful before grouping.
df["half_hour"] = df["when"].dt.floor("30min")
df["day_start"] = df["when"].dt.normalize()
print(df[["when", "half_hour", "day_start"]])floorrounds down,ceilrounds up, androundgoes to the nearest step.normalize()sets the time of day to midnight and keeps the dtype asdatetime64. It is the quickest way to get "the day" as a timestamp.- The frequency argument uses the same aliases as
date_range, such as"30min"or"D".
Compare normalize() with dt.date. The date property returns Python date objects stored in an object column. That column loses vectorized speed and cannot use .dt afterward. Prefer normalize() unless you truly need Python date objects.
ISO calendar values
dt.isocalendar() returns a DataFrame with the columns year, week, and day, following the ISO 8601 week rules.
iso = df["when"].dt.isocalendar()
print(iso)For 2024-12-31, the ISO year is 2025 and the ISO week is 1, because ISO weeks start on Monday and week 1 is the week containing the first Thursday of the year. If you build weekly reports from the calendar year and the ISO week together, you will get 2024 paired with week 1 for late December dates. Use the ISO year column instead of dt.year when you pair it with the ISO week.
The old dt.week and dt.weekofyear properties were removed in pandas 2.0, so use isocalendar().week in current code. The result dtype is an unsigned nullable integer, which supports missing values.
Formatting with strftime
dt.strftime(format) turns datetimes into strings using the same format codes as Python's datetime.
df["label"] = df["when"].dt.strftime("%Y-%m")
print(df[["when", "label"]])The result is an object column of strings, so it no longer has any datetime behavior. Use it at the end of a pipeline for display or file output. For grouping, prefer the numeric components or to_period. Strings in %Y-%m order do sort correctly, but formats like %m/%Y do not.
Missing values and NaT
Missing times are stored as NaT (not a time). Integer components cannot hold a missing value in a plain NumPy integer column, so pandas returns floats with NaN in those positions.
s = pd.to_datetime(pd.Series(["2024-01-15", "not a date"]), errors="coerce")
print(s.dt.month)
print(s.dt.month.astype("Int64"))
print(s.dt.day_name())The first print shows 1.0 and NaN with dtype float64. The second print converts to the nullable Int64 dtype, which shows 1 and <NA>. The day_name() result has NaN in the missing row.
Two consequences follow:
- A column that was integer-valued suddenly becomes float when a single
NaTappears, so later code that expects integers can misbehave. - Comparisons such as
dt.month == 1giveFalseforNaTrows, so those rows silently drop out of filters. Count them withs.isna().sum()before you trust a filtered total.
Time zones: components are local wall time
For a time-zone-aware column, .dt components describe the local wall-clock time in that column's zone, not UTC. The same instant therefore gives different components depending on the zone.
utc = pd.Series(pd.to_datetime(["2024-03-10 23:30"])).dt.tz_localize("UTC")
tokyo = utc.dt.tz_convert("Asia/Tokyo")
print(utc.dt.day.iloc[0], utc.dt.hour.iloc[0])
print(tokyo.dt.day.iloc[0], tokyo.dt.hour.iloc[0])
print(tokyo.dt.tz)The UTC value is day 10 at hour 23. The Tokyo value is day 11 at hour 8. If you group sales by day, decide which zone defines "a day" and convert before extracting components. Inspect dt.tz to see which zone a column uses. It is None for naive values.
The same properties on a DatetimeIndex
When the datetimes are in the index, you do not use .dt. A DatetimeIndex has the same properties and methods directly on it:
ts = df.set_index("when")["amount"]
print(ts.index.year)
print(ts.groupby(ts.index.month).sum())The index version returns an Index, not a Series, which is why groupby accepts it as an array of keys. A common mistake is writing ts.index.dt.year, which fails with an AttributeError.
Timedelta columns have a .dt accessor too
The accessor is also available on timedelta64 columns, with different properties. The next chapter covers durations in depth, but the pattern is the same:
gap = df["when"].diff()
print(gap.dt.days)
print(gap.dt.total_seconds() / 3600)dt.days returns only the whole-day part of the duration. For the full length in a single unit, use dt.total_seconds() and divide. The first row has NaT because there is no earlier row, so both results hold NaN there.
Quick debugging checklist
- Run
df.dtypes. If the column isobject, convert it first. - Count missing values with
df["when"].isna().sum()before you extract anything. - Check
dt.tzif results look shifted by hours or a whole day. - Check whether a number is a count of Mondays or Sundays by printing
dt.day_name()besidedt.dayofweekfor a few rows. - If a result column unexpectedly became float, look for
NaTin the source.
Exercise
A DataFrame has a column ts of strings like "2024-06-30 22:15". You run df["ts"].dt.month and get an AttributeError. What is wrong, and what is the fix?
Show answer
The column has an object (string) dtype, and .dt only works on datetime64 values. Convert it first with df["ts"] = pd.to_datetime(df["ts"]), then df["ts"].dt.month returns 6 for that row.
Exercise
You total amount by df["when"].dt.month on two years of data and the March total looks twice as large as expected. Why, and how can you fix it?
Show answer
dt.month is 3 for March of both years, so the two Marches are merged into one group. Group by both year and month, for example df.groupby([df["when"].dt.year, df["when"].dt.month]), or use df["when"].dt.to_period("M") as the key.
Exercise
A timestamp is "2024-03-10 23:30" in UTC. What are dt.day and dt.hour after tz_convert("Asia/Tokyo"), and why do they differ from the UTC values?
Show answer
Day 11 and hour 8. Tokyo is UTC+9, and .dt returns local wall-clock components for the column's time zone, so 23:30 UTC becomes 08:30 on the next day.