Time is everywhere in data — sales by day, events by timestamp. Pandas has first-class datetime support: parse strings to real dates, extract parts with .dt, and set a DatetimeIndex to unlock time-based selection.
Parsing & parts
df["date"] = pd.to_datetime(df["date"])df["year"] = df["date"].dt.yeardf["month"] = df["date"].dt.monthdf["dow"] = df["date"].dt.day_name()
A DatetimeIndex
Set the date as the index and you can select by time with natural, partial strings:
ts = df.set_index("date")ts.loc["2026"] # all of 2026ts.loc["2026-07"] # July 2026ts.loc["2026-01":"2026-06"] # a date range
Key takeaways
- 01pd.to_datetime parses date strings into real datetimes.
- 02The .dt accessor extracts year/month/day/day_name and more.
- 03A DatetimeIndex enables partial-string selection: ts.loc["2026-07"].
- 04Parse dates at load time — a string date can't be resampled or sorted correctly.
