Ensure the column has a datetime64 dtype with pd.to_datetime(), then access the vectorized .dt accessor—using df["date"].dt.year and df["date"].dt.month for integer numbers (2026, 11), or df["date"].dt.month_name() ("November") / df["date"].dt.strftime("%b") ("Nov") when you need text month names.
Basic Example
import pandas as pd
df = pd.DataFrame({
"order_date": ["2026-01-15", "2026-11-29", None],
"amount": [120, 350, 90],
})
# 1. Convert string/object column to datetime64 first (errors="coerce" turns invalid/None into NaT)
df["order_date"] = pd.to_datetime(df["order_date"], errors="coerce")
# 2. Recommended: Extract integer Year and Month via the vectorized `.dt` accessor
df["year"] = df["order_date"].dt.year
df["month"] = df["order_date"].dt.month
# 3. Optional: Extract full or abbreviated month names
df["month_name"] = df["order_date"].dt.month_name() # "January", "November", NaN
df["month_abbr"] = df["order_date"].dt.strftime("%b") # "Jan", "Nov", NaN
print(df)
# order_date amount year month month_name month_abbr
# 0 2026-01-15 120 2026.0 1.0 January Jan
# 1 2026-11-29 350 2026.0 11.0 November Nov
# 2 NaT 90 NaN NaN NaN NaN
Key Details & Edge Cases
AttributeError: Can only use .dt accessor with datetimelike values:- If your column is stored as strings (
objectorstringdtype) or Pythondatetime.dateobjects, callingdf["col"].dt.yearraisesAttributeError. Always normalize it first withdf["col"] = pd.to_datetime(df["col"], errors="coerce").
- If your column is stored as strings (
- Missing
NaTvalues cast.dt.yearand.dt.monthtofloat64(2026.0,11.0) unless using nullable"Int64":- Standard NumPy integer columns (
int64) cannot storeNaN, so if any row containsNaT, Pandas returnsfloat64(2026.0). Cast to Pandas’ nullable integer dtype with.astype("Int64")(df["year"] = df["order_date"].dt.year.astype("Int64")) to keep clean integers (2026,11,<NA>).
- Standard NumPy integer columns (
- Timezone-aware datetimes (
datetime64[ns, UTC]or local offsets):.dt.yearand.dt.monthevaluate in the column’s attached timezone. If your column is in UTC (2026-12-01 01:00:00+00:00) but you need local calendar months (e.g.,Asia/Karachi), convert first withdf["order_date"].dt.tz_convert("Asia/Karachi").dt.month.
- Grouping or sorting by Year-Month together (
Periodvs. separate integers):- Sorting by
month_namesorts alphabetically ("April"before"January"). For chronological monthly aggregations (groupby) or time-series plotting, either group by["year", "month"]or create a monthly period column viadf["year_month"] = df["order_date"].dt.to_period("M")(2026-01,2026-11).
- Sorting by
- Never use
df["order_date"].apply(lambda x: x.year):- Row-wise
.apply()runs a slow Python loop over every row and fails onNaTunless guarded, whereas.dt.yearand.dt.monthexecute in vectorized C/Cython code orders of magnitude faster.
- Row-wise
Comparison of Pandas .dt Year & Month Extraction Properties
| Expression | Output Example | Output Dtype (No NaT / With NaT) |
Preserves Chronological Sort Order? | Best Used When |
|---|---|---|---|---|
s.dt.year / s.dt.month (Recommended) |
2026 / 11 |
int32/int64 (or float64 / .astype("Int64")) |
Yes (numeric 1–12) |
Filtering, numeric features, multi-column groupby(["year", "month"]), and database exports. |
s.dt.month_name() |
"November" |
object / string |
No (sorts alphabetically) | Human-readable reports, chart axis labels, and UI tables. |
s.dt.strftime("%Y-%m") |
"2026-11" |
object / string |
Yes (zero-padded ISO YYYY-MM) |
Formatted string labels or CSV exports combining year and month. |
s.dt.to_period("M") |
2026-11 (Period) |
period[M] |
Yes (native period arithmetic) | Time-series monthly aggregations, resampling, and gap-free monthly indexing. |
You must log in or register to comment.
