3 · Datetimes & resampling
pandas' DatetimeIndex is the workhorse of time series: parse dates, change frequency with resample, and fill gaps — the plumbing every forecast depends on.
A DatetimeIndex unlocks time-aware operations: resample() changes frequency (downsample by aggregating, upsample by filling), and a fixed, gap-free frequency is a precondition for every classical model.
Without this:
Irregular timestamps and missing dates silently break ARIMA, seasonal_decompose, and lag features; getting the index onto a clean, regular frequency is step zero.
Before you model anything, the time axis must be clean. pandas makes this its specialty via the DatetimeIndex.
- Parsing.
pd.to_datetimeturns strings into real timestamps you can compare, sort, and slice (ts["2025-03"]selects all of March). - Frequency. A series should sit on a regular frequency — daily
"D", business-daily"B", monthly-start"MS", hourly"H". Classical models assume evenly-spaced points with no gaps. - Resampling.
resample()is groupby for time. Downsample (e.g. daily → weekly) by aggregating:ts.resample("W").mean(). Upsample (e.g. daily → hourly) by introducing new timestamps and filling them (.ffill(),.interpolate()).
Resampling is how you match a series to the horizon you care about (forecast weekly demand from daily data), smooth noise, or align two series onto the same clock. Below we generate noisy daily data, downsample to weekly, and show filling a gap — the everyday plumbing of time-series work.
Python (in browser)
DatetimeIndex superpowers: string slicing, resample() to change frequency, and asfreq()+interpolate() to get a clean gap-free series models require.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
You have daily sales but need a weekly demand forecast. What's the right pandas operation to get weekly totals?
- A DatetimeIndex enables time-aware slicing, resampling, and frequency operations — the foundation of pandas time series.
- resample() is groupby-for-time: downsample by aggregating (.mean/.sum), upsample by filling (.ffill/.interpolate).
- Classical models need a regular, gap-free frequency — use asfreq() + a fill method to get there first.
Every forecasting pipeline starts by parsing dates, fixing the frequency, and resampling to the target horizon before any model sees the data.
If you remove it: Irregular or gappy timestamps silently corrupt seasonal_decompose, ARIMA, and lag features — garbage in, garbage out.