Sub topic 7
Building regular time axes with date_range
This chapter assumes you can create pandas Series and DataFrames, and that you know what a DatetimeIndex is from the previous chapter. It covers pd.date_range, the function that generates evenly spaced timestamps. Frequency aliases get a fuller treatment in the next chapter.
Why generate a time axis
Real data often has gaps or irregular timestamps. A regular axis gives you a reference grid. You can build a series on it, reindex messy data onto it to expose missing periods, or use it as the index for test data.
pd.date_range returns a DatetimeIndex. You describe the range with three of these four pieces: start, end, periods, and freq. Pandas works out the fourth.
Start, periods, and freq
The most common form gives a start, a number of periods, and a frequency.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=5, freq="D")
print(idx)freq="D" means calendar days. The result has five timestamps, from 2024-01-01 to 2024-01-05, all at midnight.
If you leave freq out, it defaults to "D".
Start and end
You can give both ends instead of a count. Pandas fills in every step between them, and the end is included if it lands on the grid.
idx = pd.date_range("2024-01-01", "2024-01-10", freq="D")
print(len(idx))This prints 10, because both endpoints are inclusive.
Using end and periods
If you know where the series should finish, give end and periods. Pandas counts backward.
idx = pd.date_range(end="2024-03-31", periods=3, freq="ME")
print(idx)This gives the last three month-ends up to and including 2024-03-31. The alias "ME" means month end. Older pandas versions (before 2.2) spell it "M".
Evenly spaced without a frequency
If you give start, end, and periods but no freq, pandas spaces the points evenly across the interval.
idx = pd.date_range("2024-01-01", "2024-01-02", periods=5)
print(idx)The five points fall every six hours. This is useful when you need a fixed number of samples rather than a fixed step.
Common frequencies
| Alias | Meaning |
|---|---|
| `D` | Calendar day |
| `B` | Business day (Monday to Friday) |
| `h` | Hour |
| `min` | Minute |
| `W` | Weekly, anchored on Sunday |
| `ME` | Month end |
| `MS` | Month start |
A multiple works as a prefix, so "15min" means every 15 minutes and "2D" means every other day.
print(pd.date_range("2024-01-01", periods=5, freq="B"))
print(pd.date_range("2024-01-01 09:00", periods=4, freq="15min"))The business-day range skips the weekend. January 1, 2024 is a Monday, so five business days end on Friday, January 5. Business days ignore holidays unless you use a custom calendar.
Normalizing and naming
By default, the time of day of start is kept. A start of "2024-01-01 09:30" with daily frequency gives 09:30 on every day. To snap every timestamp to midnight, pass normalize=True. You can also name the index with name, which becomes the index name when you use it in a Series.
idx = pd.date_range("2024-01-01 09:30", periods=3, freq="D", normalize=True, name="day")
s = pd.Series([1.0, 2.0, 3.0], index=idx)
print(s)Putting a range to work: finding gaps
A frequent use is reindexing observed data onto a full grid. Missing periods then show up as NaN.
observed = pd.Series(
[10, 12, 9],
index=pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05"]),
)
full = pd.date_range("2024-01-01", "2024-01-05", freq="D")
print(observed.reindex(full))January 3 and 4 appear with NaN, so you can see exactly which days are missing.
Exercise
Write a call to pd.date_range that returns 4 timestamps, one per month start, beginning at 2024-02-01. What is the last timestamp?
Show answer
pd.date_range("2024-02-01", periods=4, freq="MS"). The last timestamp is 2024-05-01.
Exercise
What does pd.date_range("2024-06-01", "2024-06-03", periods=3) return, and why does it need no freq?
Show answer
It returns 2024-06-01, 2024-06-02 and 2024-06-03. With start, end and periods given, pandas spaces the points evenly across the interval, so it computes the step itself.