Python pandas – Create a date range

In this post we will be creating a Python script that will use the pandas library to create a date range. This date range could be from todays date or between two predefined dates. Pandas has an extremely useful ‘date_range()‘ function which will return a list of equally spaced time points.

See the snippet of Python code below that will generate a date range in list from today to ten days in the future.

import pandas as pd
from datetime import datetime

daterange = pd.date_range(datetime.today(), periods=10).tolist()

for date in daterange:
    print(date)

The above would return the following as output.

2022-12-09 09:26:51.925495
2022-12-10 09:26:51.925495
2022-12-11 09:26:51.925495
2022-12-12 09:26:51.925495
2022-12-13 09:26:51.925495
2022-12-14 09:26:51.925495
2022-12-15 09:26:51.925495
2022-12-16 09:26:51.925495
2022-12-17 09:26:51.925495
2022-12-18 09:26:51.925495
>>> 

If your interested instead in defining your range entirely refer to the snippet of code below.

import pandas as pd
from datetime import datetime

daterange = pd.date_range(start="2022-05-05",end="2022-05-15").tolist()

for date in daterange:
    print(date)

The above would return the following as output.

2022-05-05 00:00:00
2022-05-06 00:00:00
2022-05-07 00:00:00
2022-05-08 00:00:00
2022-05-09 00:00:00
2022-05-10 00:00:00
2022-05-11 00:00:00
2022-05-12 00:00:00
2022-05-13 00:00:00
2022-05-14 00:00:00
2022-05-15 00:00:00
>>> 

Take a look at some of our other content around the Python programming language here. Or check out our Pandas crash course by clicking here instead.

Leave a Reply