# Working With Time Series — NumPy / Pandas / scikit-learn

Source: https://www.skillbyai.com/en/numpy-pandas-sklearn/g-time

> Dates as an index.

## resample and rolling windows

With a **DatetimeIndex**, `resample("D")` or `resample("W")` aggregates by calendar period (empty days appear with 0 for sum), and `rolling("2D")` computes moving-window statistics based on time rather than row count. The `.dt` accessor or index properties give parts of dates (day name, month, hour). Be explicit about time zones with `tz_localize` and `tz_convert`.

## Daily and weekly totals and a rolling window, run

I ran this with Python 3.12.3 and pandas 3.0.6. Daily totals include an empty 3 March; weeks end on Sunday by default; the 2-day rolling sum resets after gaps.

```python
import pandas as pd

ts = pd.DataFrame({
    "ts": pd.to_datetime(["2026-03-01 09:00", "2026-03-01 17:30", "2026-03-02 10:15",
                          "2026-03-04 12:00", "2026-03-08 08:45"]),
    "amount": [100, 50, 70, 30, 90],
}).set_index("ts")
print(ts.resample("D")["amount"].sum().head(4))
print(ts.resample("W")["amount"].sum())
print(ts["amount"].rolling("2D").sum().tolist())
print(ts.index.day_name().tolist())
```

Output:

```
ts
2026-03-01    150
2026-03-02     70
2026-03-03      0
2026-03-04     30
Freq: D, Name: amount, dtype: int64
ts
2026-03-01    150
2026-03-08    190
Freq: W-SUN, Name: amount, dtype: int64
[100.0, 150.0, 220.0, 30.0, 90.0]
['Sunday', 'Sunday', 'Monday', 'Wednesday', 'Sunday']
```

## Store timestamps in UTC

Convert to local time only for display; mixing zones silently shifts aggregations.

**Quiz:** What does resample("W") do by default?

- [ ] Shifts dates by a week
- [ ] Keeps one row per weekday
- [x] Aggregates into weeks ending on Sunday
- [ ] Removes weekends

*Answer:* Aggregates into weeks ending on Sunday. Weekly bins, W-SUN.
