Time is everywhere in data — sales by day, sign-ups by week, metrics by minute. Pandas has exceptional time-series support: make dates the index and a whole vocabulary of resampling and rolling operations opens up.
The DatetimeIndex
Parse a date column and set it as the index. A DatetimeIndex unlocks time-based selection and slicing:
df["date"] = pd.to_datetime(df["date"])ts = df.set_index("date").sort_index()ts.loc["2026"] # every row in 2026ts.loc["2026-07"] # just July 2026ts.loc["2026-01":"2026-03"] # a date range (inclusive)pd.date_range("2026-01-01", periods=12, freq="MS") # month starts
The .dt accessor
df["year"] = df["date"].dt.yeardf["month"] = df["date"].dt.month_name()df["weekday"] = df["date"].dt.day_name()df["is_weekend"] = df["date"].dt.dayofweek >= 5
Resampling
resample is groupby for time — roll daily data up to monthly, or fill gaps in sparse data. It needs a DatetimeIndex:
ts["sales"].resample("MS").sum() # monthly totalsts["sales"].resample("W").mean() # weekly averagests["sales"].resample("D").ffill() # daily, forward-filling gaps# Common freq codes: D day, W week, MS month-start, QS quarter, YS year
Rolling windows
A rolling window smooths noisy series and reveals trend — a 7-day moving average is the classic example:
ts["sales"].rolling(7).mean() # 7-period moving averagets["sales"].rolling(30).std() # 30-period volatilityts["sales"].pct_change() # period-over-period % changets["sales"].diff() # absolute change vs previous
Practice
Load a dated dataset, parse the dates and set a sorted DatetimeIndex. Slice a single month with .loc. Resample daily values to monthly totals, then add a 7-day rolling average and a period-over-period pct_change column.
Key takeaways
- 01Parse dates with to_datetime and set a sorted DatetimeIndex for time-based slicing.
- 02ts.loc["2026-07"] selects by partial date strings; date_range generates date sequences.
- 03The .dt accessor extracts year/month/weekday and boolean flags like is_weekend.
- 04resample is groupby for time — change frequency (D/W/MS/QS) with an aggregation.
- 05rolling windows smooth series (moving averages); pct_change and diff measure change.
