Skip to main content
Albero Academy

Working with Dates

Parse dates, use the .dt accessor, and index by time.

Time Series & Advanced9 min

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

to_datetime and .dt
df["date"] = pd.to_datetime(df["date"])
df["year"] = df["date"].dt.year
df["month"] = df["date"].dt.month
df["dow"] = df["date"].dt.day_name()

A DatetimeIndex

Set the date as the index and you can select by time with natural, partial strings:

time-based selection
ts = df.set_index("date")
ts.loc["2026"] # all of 2026
ts.loc["2026-07"] # July 2026
ts.loc["2026-01":"2026-06"] # a date range

Key takeaways

  1. 01pd.to_datetime parses date strings into real datetimes.
  2. 02The .dt accessor extracts year/month/day/day_name and more.
  3. 03A DatetimeIndex enables partial-string selection: ts.loc["2026-07"].
  4. 04Parse dates at load time — a string date can't be resampled or sorted correctly.

Finished this chapter?

Mark it complete to track your progress through Pandas.