Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Generate dates in a range
Pandas date_range() function generates a sequence of dates within a specified range. This is useful for creating time series data, filtering datasets by date periods, or setting up date indexes for analysis.
Syntax
pd.date_range(start, end, periods, freq)
Parameters
The key parameters are:
- start − Starting date of the range
- end − Ending date of the range
- periods − Number of dates to generate
- freq − Frequency (default is 'D' for daily)
Generating Dates with Periods
Generate 10 consecutive dates starting from a specific date ?
import pandas as pd
# Generate 10 dates starting from June 1, 2021
dates = pd.date_range('6/1/2021', periods=10)
print("Displaying dates in a range:\n", dates)
Displaying dates in a range:
DatetimeIndex(['2021-06-01', '2021-06-02', '2021-06-03', '2021-06-04',
'2021-06-05', '2021-06-06', '2021-06-07', '2021-06-08',
'2021-06-09', '2021-06-10'],
dtype='datetime64[ns]', freq='D')
Generating Dates with Start and End
Specify both start and end dates to generate all dates between them ?
import pandas as pd
# Generate dates between two specific dates
dates = pd.date_range(start='2021-06-01', end='2021-06-10')
print("Dates between start and end:\n", dates)
Dates between start and end:
DatetimeIndex(['2021-06-01', '2021-06-02', '2021-06-03', '2021-06-04',
'2021-06-05', '2021-06-06', '2021-06-07', '2021-06-08',
'2021-06-09', '2021-06-10'],
dtype='datetime64[ns]', freq='D')
Using Different Frequencies
Generate dates with weekly frequency instead of daily ?
import pandas as pd
# Generate weekly dates
weekly_dates = pd.date_range('2021-06-01', periods=8, freq='W')
print("Weekly dates:\n", weekly_dates)
Weekly dates:
DatetimeIndex(['2021-06-06', '2021-06-13', '2021-06-20', '2021-06-27',
'2021-07-04', '2021-07-11', '2021-07-18', '2021-07-25'],
dtype='datetime64[ns]', freq='W-SUN')
Common Frequency Options
| Frequency | Description | Example |
|---|---|---|
| 'D' | Daily | 2021-06-01, 2021-06-02... |
| 'W' | Weekly | 2021-06-06, 2021-06-13... |
| 'M' | Monthly | 2021-06-30, 2021-07-31... |
| 'H' | Hourly | 2021-06-01 00:00, 01:00... |
Conclusion
Use pd.date_range() to generate sequential dates by specifying start date with periods, or start and end dates. The freq parameter controls the interval between dates.
Advertisements
