How do you extract Month and Year as separate columns from a Pandas datetime column? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

"How do you extract Month and Year as separate columns from a Pandas datetime column?

message-square
0

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 (object or string dtype) or Python datetime.date objects, calling df["col"].dt.year raises AttributeError. Always normalize it first with df["col"] = pd.to_datetime(df["col"], errors="coerce").
  • Missing NaT values cast .dt.year and .dt.month to float64 (2026.0, 11.0) unless using nullable "Int64":
    • Standard NumPy integer columns (int64) cannot store NaN, so if any row contains NaT, Pandas returns float64 (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>).
  • Timezone-aware datetimes (datetime64[ns, UTC] or local offsets):
    • .dt.year and .dt.month evaluate 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 with df["order_date"].dt.tz_convert("Asia/Karachi").dt.month.
  • Grouping or sorting by Year-Month together (Period vs. separate integers):
    • Sorting by month_name sorts alphabetically ("April" before "January"). For chronological monthly aggregations (groupby) or time-series plotting, either group by ["year", "month"] or create a monthly period column via df["year_month"] = df["order_date"].dt.to_period("M") (2026-01, 2026-11).
  • Never use df["order_date"].apply(lambda x: x.year):
    • Row-wise .apply() runs a slow Python loop over every row and fails on NaT unless guarded, whereas .dt.year and .dt.month execute in vectorized C/Cython code orders of magnitude faster.

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.