Pandas pd.date_range() function
pd.date_range() is a function in the Pandas library used togenerate a date range. It can create a DatetimeIndex containing consecutive dates, commonly used for the creation, indexing, and alignment of time series data.
In time series analysis, it is often necessary to generate date sequences with a fixed frequency, such as daily, monthly, or yearly data. pd.date_range() provides flexible parameters to meet various frequency requirements.
Word meaning: date_range means "date range", i.e., generating a set of consecutive dates.
Basic syntax and parameters
pd.date_range() is a top-level function in the Pandas library used to generate a datetime index with a specified frequency.
Syntax format
pd.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| start | String or datetime | Optional | The start date. | None |
| end | String or datetime | Optional | The end date. | None |
| periods | Integers | Optional | The number of dates to generate. Specify two of the three (start, end, periods). | None |
| freq | String or DateOffset | Optional | Frequency: 'D' (day), 'H' (hour), 'M' (month end), 'MS' (month start), 'Y' (year end), 'W' (week), etc. | 'D' |
| tz | String | Optional | Time zone name, such as 'UTC' or 'Asia/Shanghai'. | None |
| normalize | Boolean | Optional | If True, normalize the times to midnight. | False |
| name | String | Optional | The name of the generated DatetimeIndex. | None |
| closed | String | Optional | Interval closure: 'left', 'right', None (both closed by default). | None |
Return value description
- Return Value: Returns a DatetimeIndex object containing consecutive datetimes.
- effect: Generates a date sequence based on the specified start date, end date, and frequency.
Example
Let us thoroughly master pd.date_range() through a series of examples from simple to complex.
Example 1: Basic usage - generate a date range
Example
import
pandas
as
pd
1. Use the start and end parameters to generate a date range (default frequency is daily)
(
"=== From 2023-01-01 to 2023-01-10 ==="
)
dates
=
pd.
date_range
(
start
=
'2023-01-01'
,
end
=
'2023-01-10'
)
(
dates
)
(
f
"Type: {type(dates)}"
)
(
f
"Data type: {dates.dtype}"
)
2. Use the periods parameter to specify the count to generate
(
"n=== Generate 7 days of dates ==="
)
week_dates
=
pd.
date_range
(
start
=
'2023-01-01'
,
periods
=
7
)
(
week_dates
)
3. Use the freq parameter to specify the frequency
(
"n=== One date per week (freq='W') ==="
)
weekly_dates
=
pd.
date_range
(
start
=
'2023-01-01'
,
periods
=
5
,
freq
=
'W'
)
(
weekly_dates
)
4. Dates at the start of each month (freq='MS' = Month Start)
(
"n=== Start of each month (freq='MS') ==="
)
monthly_dates
=
pd.
date_range
(
start
=
'2023-01-01'
,
periods
=
6
,
freq
=
'MS'
)
(
monthly_dates
)
5. Dates at the end of each year (freq='YE' = Year End)
(
"n=== End of each year (freq='YE') ==="
)
yearly_dates
=
pd.
date_range
(
start
=
'2023-01-01'
,
periods
=
3
,
freq
=
'YE'
)
(
yearly_dates
)
Result:
=== 从 2023-01-01 到 2023-01-10 ===
DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05',
'2023-01-06', '2023-01-07', '2023-01-08', '2023-01-09', '2023-01-10'],
dtype='datetime64[ns]', freq='D')
类型:
数据类型: datetime64[ns]
=== 生成 7 天的日期 ===
DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05',
'2023-01-06', '2023-01-07'], dtype='datetime64[ns]', freq='D')
=== 每周一个日期 (freq='W') ===
DatetimeIndex(['2023-01-01', '2023-01-08', '2023-01-15', '2023-01-22', '2023-01-29'], dtype='datetime64[ns]', freq='W-SUN')
=== 每月初 (freq='MS') ===
DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01', '2023-05-01',
'2023-06-01'], dtype='datetime64[ns]', freq='MS')
=== 每年末 (freq='YE') ===
DatetimeIndex(['2023-12-31', '2024-12-31', '2025-12-31'], dtype='datetime64[ns]', freq='YE-DEC')
Code analysis:
pd.date_range()By default, a date sequence with daily frequency is generated.freqThe parameter supports various frequency abbreviations: 'D' (day), 'W' (week), 'M' (month end), 'MS' (month start), 'Y' (year end), 'H' (hour), etc.- The returned object is a DatetimeIndex, which can be used directly as an index for a Series or DataFrame.
Example 2: Generate time series data
Create a DataFrame with a date index for time series analysis.
Example
import
pandas
as
pd
import
numpy
as
np
1. Create a DataFrame with a date index
(
"=== Create a simple time series ==="
)
Generate 30 days of dates
date_index
=
pd.
date_range
(
start
=
'2023-01-01'
,
periods
=
30
,
freq
=
'D'
)
Create DataFrame
df
=
pd.
DataFrame
(
{
'date'
: date_index
,
'value'
: np.
random
.
randint
(
10
,
100
,
size
=
30
)
,
Random values
'category'
:
[
'A'
,
'B'
]
15
Alternating categories
}
)
(
df.
head
(
10
)
)
2. Set the date as the index
(
"n=== Set date as index ==="
)
df_indexed
=
df.
set_index
(
'date'
)
(
df_indexed.
head
(
)
)
3. Generate hourly data (for log analysis)
(
"n=== Hourly time series ==="
)
hourly_index
=
pd.
date_range
(
start
=
'2023-01-01 08:00'
,
periods
=
24
,
freq
=
'H'
)
hourly_data
=
pd.
DataFrame
(
{
'timestamp'
: hourly_index
,
'visitors'
: np.
random
.
randint
(
0
,
100
,
size
=
24
)
}
)
(
hourly_data
)
Result:
=== 创建一个简单的时间序列 ===
date value category
0 2023-01-01 67 A
1 2023-01-02 23 B
2 2023-01-03 45 A
3 2023-01-04 89 B
4 2023-01-05 12 A
5 2023-01-06 34 B
6 2023-01-07 56 A
7 2023-01-08 78 B
8 2023-01-09 91 A
9 2023-01-10 55 B
=== 设置日期为索引 ===
value category
date
2023-01-01 67 A
2023-01-02 23 B
2023-01-03 45 A
2023-01-04 89 B
2023-01-05 12 A
2023-01-06 34 B
=== 每小时的时间序列 ===
timestamp visitors
0 2023-01-01 08:00:00 25
1 2023-01-01 09:00:00 41
2 2023-01-01 10:00:00 77
3 2023-01-01 11:00:00 12
4 2023-01-01 12:00:00 58
5 2023-01-01 13:00:00 33
6 2023-01-01 14:00:00 45
7 2023-01-01 15:00:00 67
8 2023-01-01 16:00:00 29
9 2023-01-01 17:00:00 51
10 2023-01-01 18:00:00 44
11 2023-01-01 19:00:00 36
12 2023-01-01 20:00:00 28
13 2023-01-01 21:00:00 62
14 2023-01-01 22:00:00 19
15 2023-01-01 23:00:00 73
16 2023-01-02 00:00:00 41
17 2023-01-02 01:00:00 55
18 2023-01-02 02:00:00 38
19 2023-01-02 03:00:00 27
20 2023-01-02 04:00:00 49
21 2023-01-02 05:00:00 63
22 2023-01-02 06:00:00 34
23 2023-01-02 07:00:00 56
Code analysis:
- A DatetimeIndex can be used directly as a DataFrame index.
- A DataFrame with a date index supports rich time series operations such as resampling and rolling calculations.
freq='H'Hourly data can be generated, suitable for scenarios such as log analysis.
Example 3: Time zone and the closed parameter
Example
import
pandas
as
pd
1. Use the tz parameter to specify the time zone
(
"=== Date range with a time zone ==="
)
dates_tz
=
pd.
date_range
(
start
=
'2023-01-01'
,
periods
=
3
,
freq
=
'D'
,
tz
=
'Asia/Shanghai'
)
(
dates_tz
)
(
f
"Time zone: {dates_tz.tz}"
)
2. Use the UTC time zone
(
"n=== UTC time zone ==="
)
dates_utc
=
pd.
date_range
(
start
=
'2023-01-01'
,
periods
=
3
,
freq
=
'D'
,
tz
=
'UTC'
)
(
dates_utc
)
3. Use the closed parameter to control interval closure
(
"n=== closed parameter comparison ==="
)
(
"closed=None (default, both ends closed):"
,
pd.
date_range
(
'2023-01-01'
,
'2023-01-03'
,
freq
=
'D'
,
closed
=
None
)
)
(
"closed='left':"
,
pd.
date_range
(
'2023-01-01'
,
'2023-01-03'
,
freq
=
'D'
,
closed
=
'left'
)
)
(
"closed='right':"
,
pd.
date_range
(
'2023-01-01'
,
'2023-01-03'
,
freq
=
'D'
,
closed
=
'right'
)
)
4. Use the normalize parameter to normalize times
(
"n=== normalize parameter ==="
)
dates_with_time
=
pd.
date_range
(
start
=
'2023-01-01 14:30:00'
,
periods
=
3
,
freq
=
'H'
)
(
"Before normalization:"
,
dates_with_time
)
dates_normalized
=
pd.
date_range
(
start
=
'2023-01-01 14:30:00'
,
periods
=
3
,
freq
=
'H'
,
normalize
=
True
)
(
"After normalization:"
,
dates_normalized
)
Result:
=== 带时区的日期范围 ===
DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03'], dtype='datetime64[ns, Asia/Shanghai]')
时区: Asia/Shanghai
=== UTC 时区 ===
DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03'], dtype='datetime64[ns, UTC]')
=== closed 参数对比 ===
closed=None (默认, 两端都闭): DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03'])
closed='left': DatetimeIndex(['2023-01-01', '2023-01-02'])
closed='right': DatetimeIndex(['2023-01-02', '2023-01-03'])
=== normalize 参数 ===
归一化前: DatetimeIndex(['2023-01-01 14:30:00', '2023-01-01 15:30:00', '2023-01-01 16:30:00'])
归一化后: DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03'])
Code analysis:
tzThe parameter can specify a time zone, which is very useful when working with data across time zones.closedThe parameter can control interval closure, with both ends closed by default.normalize=TrueNormalize times to midnight, making it easy to aggregate data by date.
Notes
Important note:
start and end, or specify start and periods, or specify end and periods, but not just one of them at the same time.
Common Pandas functions