Pandas - Generate date range

By xngo on February 19, 2020

With Pandas, you can generate dates range using pandas.date_range(). For the example below, it will generate dates from 2020-01-01 to 2020-02-28 but will skip weekends.

#!/usr/bin/python3
import pandas as pd
 
# Generate dates from 2020-01-01 to 2020-02-28
#   but return business day only(freq="B").
d = pd.date_range(start="2020-01-01", end="2020-01-15", freq="B")
 
print(d)

Output

DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-06',
               '2020-01-07', '2020-01-08', '2020-01-09', '2020-01-10',
               '2020-01-13', '2020-01-14', '2020-01-15'],
              dtype='datetime64[ns]', freq='B')

References

  • pandas.date_range(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html
  • frequency aliases: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.