DatetimeIndex and Period Ranges
Create a DatetimeIndex with pd.date_range, parse string dates, and set a time column as the index for time-based access.
Why Pandas Has Special Time Tools
Time series data requires more than just storing dates as strings. You need to sort by time, select date ranges, resample to different frequencies, and extract components like month and weekday. Pandas addresses this with the DatetimeIndex — an index made of datetime64 values — which unlocks specialised time-aware operations not available on ordinary integer or string indices.
Creating a DatetimeIndex with pd.date_range()
pd.date_range(start, end, freq) generates a sequence of evenly-spaced dates. The freq parameter specifies the interval using offset aliases: 'D' for day, 'h' for hour, 'ME' for month end, 'W' for week, 'YE' for year end. You can pass either end or periods (number of timestamps) — not both.
import pandas as pd
# Daily dates for January 2024
dates = pd.date_range(start='2024-01-01', end='2024-01-07', freq='D')
print(dates)
# DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03',
# '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07'],
# dtype='datetime64[ns]', freq='D')
# 12 month-end dates
months = pd.date_range(start='2024-01-31', periods=12, freq='ME')
print(months[:3])All lessons in this course
- DatetimeIndex and Period Ranges
- Resampling Time Series
- Shifting and Lag Features
- Extracting Temporal Features