We use date ranges to create a list of dates between two points in time. This helps us analyze data over days, weeks, or months easily.
0
0
Date range creation with date_range in Pandas
Introduction
You want to create a calendar of dates for a report.
You need to fill missing dates in a time series dataset.
You want to generate dates for scheduling or planning.
You want to analyze data trends over a specific period.
You want to create time-based indexes for data frames.
Syntax
Pandas
pandas.date_range(start=None, end=None, periods=None, freq='D')
start: The first date in the range.
end: The last date in the range.
periods: Number of dates to generate (optional if start and end are given).
freq: Frequency of dates, 'D' means daily (default).
Examples
This creates dates from January 1 to January 5, 2024, one day apart.
Pandas
import pandas as pd # Create daily dates from Jan 1 to Jan 5, 2024 dates = pd.date_range(start='2024-01-01', end='2024-01-05') print(dates)
This creates 4 daily dates starting from January 1, 2024.
Pandas
import pandas as pd # Create 4 dates starting from Jan 1, 2024, daily frequency dates = pd.date_range(start='2024-01-01', periods=4) print(dates)
This creates dates every 2 days between January 1 and January 9, 2024.
Pandas
import pandas as pd # Create dates every 2 days from Jan 1 to Jan 9, 2024 dates = pd.date_range(start='2024-01-01', end='2024-01-09', freq='2D') print(dates)
Sample Program
This program creates 7 daily dates starting from June 1, 2024, and shows them in a table.
Pandas
import pandas as pd # Create a date range for one week starting from 2024-06-01 dates = pd.date_range(start='2024-06-01', periods=7) # Convert to a DataFrame to show nicely df = pd.DataFrame({'Date': dates}) print(df)
OutputSuccess
Important Notes
If you provide both start and end, periods is ignored.
You can use other frequencies like 'H' for hourly, 'M' for month end, or 'W' for weekly.
The output is a DatetimeIndex, which works well with pandas data frames.
Summary
date_range helps create a list of dates easily.
You can control start, end, number of dates, and frequency.
This is useful for time-based data analysis and filling missing dates.