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 list comprehension.

For instance, we write

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

to create a datetime object with today’s date with

base = datetime.datetime.today()

Then we create the datetime list with

[base - datetime.timedelta(days=x) for x in range(num_days)]

We subtract the number of days from base to get the datetime values.

Conclusion

To create a range of dates in Python, we can use 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 *