Skip to main content
Albero Academy

Time Series & Dates

Work with dates as a first-class index — parse and generate dates, resample to new frequencies, and compute rolling trends.

Chapter 7Pandas16 min readBeginner friendly
  • #Pandas
  • #Time Series
  • #Dates

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:

dates as the index
df["date"] = pd.to_datetime(df["date"])
ts = df.set_index("date").sort_index()
ts.loc["2026"] # every row in 2026
ts.loc["2026-07"] # just July 2026
ts.loc["2026-01":"2026-03"] # a date range (inclusive)
pd.date_range("2026-01-01", periods=12, freq="MS") # month starts

The .dt accessor

pulling date parts
df["year"] = df["date"].dt.year
df["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:

change the frequency
ts["sales"].resample("MS").sum() # monthly totals
ts["sales"].resample("W").mean() # weekly averages
ts["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:

moving averages & change
ts["sales"].rolling(7).mean() # 7-period moving average
ts["sales"].rolling(30).std() # 30-period volatility
ts["sales"].pct_change() # period-over-period % change
ts["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

  1. 01Parse dates with to_datetime and set a sorted DatetimeIndex for time-based slicing.
  2. 02ts.loc["2026-07"] selects by partial date strings; date_range generates date sequences.
  3. 03The .dt accessor extracts year/month/weekday and boolean flags like is_weekend.
  4. 04resample is groupby for time — change frequency (D/W/MS/QS) with an aggregation.
  5. 05rolling windows smooth series (moving averages); pct_change and diff measure change.