Coding Ref

What is date_range() in Pandas?

What is date_range() in Pandas?

The date_range() function in Pandas is used to generate a sequence of dates within a specified date range. This is often used to create a time series, which is a series of data points indexed by time.

Here's an example of using the date_range() function in Pandas:

main.py
import pandas as pd

# generate a sequence of dates from 2020-01-01 to 2020-01-05
dates = pd.date_range('2020-01-01', '2020-01-05')

# display the dates
print(dates)

This will generate a sequence of 5 dates starting from 2020-01-01 and ending at 2020-01-05.

The output will be:

output
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
               '2020-01-05'],
              dtype='datetime64[ns]', freq='D')

You can also specify the frequency of the date range by using the freq parameter.

For example, to generate a sequence of daily dates with a frequency of 2 days, you can do:

main.py
# generate a sequence of dates with a frequency of 2 days
dates = pd.date_range('2020-01-01', '2020-01-05', freq='2D')

# display the dates
print(dates)

This will generate a sequence of 3 dates starting from 2020-01-01 and ending at 2020-01-05, with a frequency of 2 days.

The output will be:

output
DatetimeIndex(['2020-01-01', '2020-01-03', '2020-01-05'], dtype='datetime64[ns]', freq='2D')

You can also use the date_range() function to generate a sequence of dates with a specific time span, rather than a specific end date. For example, to generate a sequence of dates for the next 5 days, you can do:

main.py
# generate a sequence of dates for the next 5 days
dates = pd.date_range('today', periods=5)

# display the dates
print(dates)

This will generate a sequence of 5 dates starting from today and ending 5 days from today.

The output will be:

output
DatetimeIndex(['2022-12-08 15:49:45.660486', '2022-12-09 15:49:45.660486',
               '2022-12-10 15:49:45.660486', '2022-12-11 15:49:45.660486',
               '2022-12-12 15:49:45.660486'],
              dtype='datetime64[ns]', freq='D')

You'll also like

Related tutorials curated for you

    How to use pandas map() function

    What is isna() in Pandas?

    What is .notnull in Pandas?

    How to use applymap() in Pandas

    How to use ffill() in Pandas

    How to give multiple conditions in loc() in Pandas

    How to drop an index column in Pandas

    What is nlargest() in Pandas?

    How to sort a series in Pandas

    fillna() in Pandas

    How to groupby mean in Pnadas

    How to stack two Pandas DataFrames