Categories
Python Answers

How to create a range of dates in Python?

Spread the love

Sometimes, we want to create a range of dates in Python.

In this article, we’ll look at how to create a range of dates in Python.

How to create a range of dates in Python?

To create a range of dates in Python, we can use the datetime module with list comprehension.

For instance, we write:

import datetime

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(10)]
print(date_list)

We call datetime.datetime.today to get today’s `date and time.

Then we compute the date from 9 days before today to today by using base - datetime.timedelta(days=x) for x in range(10).

And then we put the values into a list.

Therefore, date_list is:

[datetime.datetime(2021, 10, 24, 19, 15, 0, 832006), datetime.datetime(2021, 10, 23, 19, 15, 0, 832006), datetime.datetime(2021, 10, 22, 19, 15, 0, 832006), datetime.datetime(2021, 10, 21, 19, 15, 0, 832006), datetime.datetime(2021, 10, 20, 19, 15, 0, 832006), datetime.datetime(2021, 10, 19, 19, 15, 0, 832006), datetime.datetime(2021, 10, 18, 19, 15, 0, 832006), datetime.datetime(2021, 10, 17, 19, 15, 0, 832006), datetime.datetime(2021, 10, 16, 19, 15, 0, 832006), datetime.datetime(2021, 10, 15, 19, 15, 0, 832006)]

Conclusion

To create a range of dates in Python, we can use the datetime module with list comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *