Extract Year & Month Features From Date Strings

Basics
BasicsPandasDatetimeMetaAmazonUber

Problem

Implement add_year_month(df) returning a copy of df that parses ISO date strings in order_date using pd.to_datetime and appends integer columns year and month.

Why It Matters: Extracting calendar features (year, month, dayofweek) is fundamental for time-series forecasting, cohort grouping, and seasonality modeling.

Function Signature

import pandas as pd

def add_year_month(df: pd.DataFrame) -> pd.DataFrame:

Sample Input & Output

Example 1: Multiple Dates

Input:

order_idorder_date
12025-01-15
22026-11-30

Expected Output:

order_idorder_dateyearmonth
12025-01-1520251
22026-11-30202611

Explanation: Extracts (2025, 1) and (2026, 11) as integer columns.

Example 2: Leap Day Date

Input:

order_idorder_date
32024-02-29

Expected Output:

order_idorder_dateyearmonth
32024-02-2920242

Explanation: Parses leap-year February 29 cleanly into year = 2024, month = 2.

Constraints & Edge Cases

  • Add integer columns 'year' and 'month'.
  • Use pd.to_datetime(out['order_date']) and .dt.year / .dt.month.
  • Do not mutate df in place.

Constraints & Evaluation Criteria

  • Add integer columns `'year'` and `'month'`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
['2025-03-15', '2026-11-02']
Expected Output / Criteria
year=[2025,2026], month=[3,11]