How to Use pandas.date_range for Date Sequences
Use
pandas.date_range() to create a sequence of dates between a start and end date or for a specified number of periods. You can customize the frequency with the freq parameter to generate daily, monthly, or other intervals.Syntax
The basic syntax of pandas.date_range() is:
start: The starting date of the sequence.end: The ending date of the sequence.periods: Number of dates to generate (optional ifstartandendare given).freq: Frequency string like 'D' for daily, 'M' for month end, 'H' for hourly, etc.tz: Time zone (optional).
python
pandas.date_range(start=None, end=None, periods=None, freq='D', tz=None)
Example
This example creates a daily date range from January 1, 2024 to January 7, 2024.
python
import pandas as pd dates = pd.date_range(start='2024-01-01', end='2024-01-07') print(dates)
Output
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')
Common Pitfalls
Common mistakes include:
- Specifying both
periodsandendwhich causes an error. - Using an invalid frequency string.
- Not formatting dates as strings or
Timestampobjects.
Always provide either start and end, or start and periods, but not all three.
python
import pandas as pd # Wrong: specifying both end and periods # dates = pd.date_range(start='2024-01-01', end='2024-01-07', periods=5) # This raises an error # Right: specify start and periods correct_dates = pd.date_range(start='2024-01-01', periods=5, freq='D') print(correct_dates)
Output
DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'], dtype='datetime64[ns]', freq='D')
Quick Reference
| Parameter | Description | Example Values |
|---|---|---|
| start | Start date of the range | '2024-01-01', pd.Timestamp('2024-01-01') |
| end | End date of the range | '2024-01-07', pd.Timestamp('2024-01-07') |
| periods | Number of dates to generate | 5, 10 |
| freq | Frequency of dates | 'D' (daily), 'M' (month end), 'H' (hourly), 'W' (weekly) |
| tz | Time zone for dates | 'UTC', 'Europe/London' |
Key Takeaways
Use pandas.date_range() to create sequences of dates easily by specifying start, end, or periods.
Do not specify both end and periods together; choose one with start.
Customize the frequency with the freq parameter to get daily, monthly, or other intervals.
Input dates as strings or pandas Timestamp objects for best results.
Check frequency strings carefully to avoid errors.