Sub topic 7
Building regular time axes with date_range
This chapter assumes you can create a pandas Series and DataFrame, select rows with boolean masks, and use pd.to_datetime and a DatetimeIndex as covered in earlier chapters. It teaches you to generate evenly spaced timestamps with pd.date_range. You can then use them as indexes, as calendars to compare real data against, and as test data.
Why generate a time axis
Real data is irregular. Sensors skip readings, shops close on holidays, and logs only record events when something happens. A regular time axis gives you a complete reference calendar. Common uses:
- Create sample data for experiments without loading a file.
- Find gaps by comparing the dates you have with the dates you expected.
- Build an empty skeleton index and fill it in with
reindex. - Set the exact buckets for a report, such as every Monday at 09:00.
pd.date_range returns a DatetimeIndex. It is the same type you get from set_index on a datetime column, so everything you learned about slicing applies to it.
The four controlling parameters
date_range is controlled by four parameters: start, end, periods, and freq. You must supply enough of them to pin down the result. The rule is that exactly three of the four must be determined. freq defaults to calendar days ("D") when you give start and end without periods, so the common two-argument call works.
import pandas as pd
# start + end: every calendar day, both ends included
print(pd.date_range("2024-01-01", "2024-01-05"))
# start + periods + freq: count forward from the start
print(pd.date_range("2024-01-01", periods=4, freq="6h"))
# end + periods + freq: count backward from the end
print(pd.date_range(end="2024-03-31", periods=3, freq="MS"))The first call returns five dates. The second returns 00:00, 06:00, 12:00, and 18:00 on January 1. The third returns the three month starts at or before March 31: January 1, February 1, and March 1.
If you pass all four parameters, or too few, pandas raises a ValueError that begins "Of the four parameters: start, end, periods, and freq, exactly three must be specified". Read it as a prompt to decide which quantity you want pandas to compute.
Evenly spaced points without a frequency
When you give start, end, and periods and no freq, pandas divides the interval into equal steps, like numpy.linspace.
import pandas as pd
idx = pd.date_range("2024-01-01", "2024-01-02", periods=5)
print(idx)
print(idx.freq)The result runs from midnight on January 1 to midnight on January 2 in 6-hour steps. The freq attribute prints None, because the spacing was derived instead of named. Some methods that need a frequency, such as shift(freq=...) with no argument or asfreq, behave differently with such an index. If you need a stored frequency, pass one explicitly.
Frequency aliases
The freq argument is a string alias, optionally with a number in front. "15min" means every 15 minutes and "2h" means every 2 hours. Common aliases:
| Alias | Meaning | Example result |
|---|---|---|
| `"D"` | Calendar day | Every day |
| `"B"` | Business day (Monday to Friday) | Skips Saturday and Sunday |
| `"h"` | Hour | 00:00, 01:00, ... |
| `"min"` | Minute | 00:00, 00:01, ... |
| `"s"` | Second | 00:00:00, 00:00:01, ... |
| `"W"` | Weekly, anchored on Sunday | Every Sunday |
| `"W-MON"` | Weekly, anchored on Monday | Every Monday |
| `"MS"` | Month start | The 1st of each month |
| `"ME"` | Month end | Last day of each month |
| `"QS"` | Quarter start | Jan 1, Apr 1, Jul 1, Oct 1 |
| `"YS"` | Year start | January 1 each year |
Anchored aliases and a start that is off the grid
Aliases like "MS" and "W-MON" are anchored to calendar positions. If your start is not on the anchor, pandas moves forward to the first anchor at or after it.
import pandas as pd
print(pd.date_range("2024-01-31", periods=3, freq="MS"))
print(pd.date_range("2024-01-03", periods=3, freq="W-MON"))The first call starts at 2024-02-01, not at January 31, because the first month start on or after January 31 is February 1. The second starts at Monday, January 8. This surprises people who expect the first element to equal start. With fixed-length steps such as "6h" or "D", the first element is always start. With anchored steps it might not be.
Business days and holidays
"B" skips weekends. March 1, 2024 is a Friday, so four business days starting there cross a weekend.
import pandas as pd
print(pd.date_range("2024-03-01", periods=4, freq="B"))The output is March 1, 4, 5, and 6. For holidays, use pd.bdate_range with freq="C" (custom business day) and a list of dates to skip.
import pandas as pd
days = pd.bdate_range(
"2024-01-01", "2024-01-05", freq="C", holidays=["2024-01-02"]
)
print(days)The result is January 1, 3, 4, and 5. January 2 is removed. You can also pass weekmask, for example "Sun Mon Tue Wed Thu", for calendars with a different working week.
Controlling the endpoints
By default both ends are included when they land on the grid. The inclusive parameter changes this. It accepts "both", "left", "right", or "neither". In pandas versions before 1.4 the same idea was called closed.
import pandas as pd
print(pd.date_range("2024-01-01", "2024-01-04", inclusive="left"))This prints January 1, 2, and 3. Half-open intervals like this are useful when you build time buckets and don't want the boundary value counted in two adjacent buckets.
Normalizing to midnight
If start has a time of day and you want midnights, pass normalize=True. It resets every element to 00:00 after generation.
import pandas as pd
print(pd.date_range("2024-01-01 09:30", periods=3, freq="D", normalize=True))The output is three midnights, January 1 to 3. Without normalize, each element would be at 09:30.
Naming and time zones
The name parameter sets the index name, which becomes the column header when you call reset_index. The tz parameter creates a time-zone-aware axis directly, so you don't need tz_localize afterward.
import pandas as pd
idx = pd.date_range(
"2024-03-09", periods=3, freq="D", tz="America/New_York", name="day"
)
print(idx)Each element is midnight New York local time. The United States switched to daylight saving time on March 10, 2024. The UTC offset therefore changes from -05:00 on the first two dates to -04:00 on March 11, while the wall-clock time stays 00:00. The axis is aware of the zone's rules, so it follows local days and not a fixed number of elapsed hours.
Using a generated axis to find gaps
The most useful pattern is to compare real data to a complete calendar. Build the full range from the data's own first and last dates, reindex, and look at what is missing.
import pandas as pd
raw = pd.Series(
[5, 7, 3],
index=pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05"]),
)
full = pd.date_range(raw.index.min(), raw.index.max(), freq="D")
filled = raw.reindex(full)
print(filled)
print(filled[filled.isna()].index)reindex keeps existing values and inserts NaN for dates that had no data. The second print shows January 3 and 4 as the missing days. You can then fill them with a rule (filled.fillna(0), filled.ffill(), or filled.interpolate()), depending on what a missing value means for your data.
If you only need a regular spacing and want to fill in one step, Series.asfreq("D") does the same thing on a DatetimeIndex. Use reindex with an explicit date_range when you want control over the exact start and end, for example to extend a series to a fixed reporting window.
Edge cases and common errors
- Out of range or inconsistent endpoints. If
endis beforestartwith a positive frequency, the result is empty. It doesn't raise an error. An empty index in your output often means the endpoints are swapped. - Non-integer
periods.periodsmust be an integer. Passing a float from a calculation, such asn / 2, raises aTypeError. Convert it withint(). - Long ranges at high frequency.
freq="s"over a year creates about 31 million timestamps, which uses hundreds of megabytes of memory. Check the size withlen()on a shorter span, or compute the expected count first. - Month-end arithmetic. Adding one month with a fixed offset from January 31 is ambiguous. That's why
"ME"and"MS"exist as named anchors. Use them instead of trying to step 30 days. - Aliases that look like numbers. A frequency of
"2D"means every two days, not day 2. The number goes before the unit. - Comparing with data timestamps. If your data has times of day, a daily range built from midnight start will not match it with
reindex. Eithernormalizethe data timestamps first (.dt.normalize()) or use a range that matches their time of day.
Summary of the working model
A date_range call answers one question: which moments fall on a given rule between two points, or after a given count? Pick the parameters that match what you know. Choose an alias that names the rule. Check the first and last elements and the length, because those reveal anchoring and endpoint surprises quickly. Then use the result as an index, a reference calendar, or a skeleton for reindexing.
Exercise
You have a Series with daily values indexed by dates from 2024-02-26 to 2024-03-08, but some weekdays are missing. Write the code that finds the missing business days (Monday to Friday) in that span. Assume the Series is named sales and has a DatetimeIndex.
Show answer
Build the expected business days and take the difference with the actual index:
import pandas as pd
expected = pd.date_range(sales.index.min(), sales.index.max(), freq="B")
missing = expected.difference(sales.index)
print(missing)
freq="B" skips weekends, so weekend dates are not reported as missing. difference returns the elements of expected that are not in sales.index. Using reindex(expected) and checking for NaN also works, but it would also flag days where the stored value is itself NaN.
Exercise
What dates does pd.date_range("2024-01-31", periods=3, freq="MS") return, and why is the first one not 2024-01-31?
Show answer
It returns 2024-02-01, 2024-03-01, and 2024-04-01. "MS" is an anchored frequency that only produces month-start dates. When start is not on the anchor, pandas moves forward to the first anchor on or after it, which is February 1. Fixed-step frequencies like "D" or "6h" would start exactly at start.
Exercise
You want timestamps every 6 hours from 2024-01-01 00:00 up to but not including 2024-01-02 00:00. Which call gives exactly 4 values, and what would happen with the default inclusive?
Show answer
Use pd.date_range("2024-01-01", "2024-01-02", freq="6h", inclusive="left"). It returns 00:00, 06:00, 12:00, and 18:00 on January 1. With the default inclusive="both", the end point 2024-01-02 00:00 also lies on the grid, so you would get 5 values.