Creating a Range of Dates in Python
Suppose you need to create a list of dates, starting with today and going back a specified number of days. For example, let's create a list of 100 dates starting from today.
Inefficient Method
One way to approach this is with a simple loop:
<code class="python">import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList</code>
This method is functional but inefficient. It creates each date individually and requires multiple computations.
Optimized Method
A more efficient solution involves using list comprehension:
<code class="python">base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]</code>
This approach creates the entire list of dates at once. It utilizes a list comprehension to iterate over a range and compute each date's difference from the base date.
The optimized method is more efficient and concise, providing a simpler and faster alternative for generating a range of dates in Python.
The above is the detailed content of How to Efficiently Generate a Range of Dates in Python?. For more information, please follow other related articles on the PHP Chinese website!