I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?
import datetime
a = datetime.datetime.today()
numdays = 100
dateList = []
for x in range (0, numdays):
dateList.append(a - datetime.timedelta(days = x))
print dateList
You can write a generator function that returns date objects starting from today:
This generator returns dates starting from today and going backwards one day at a time. Here is how to take the first 3 dates:
The advantage of this approach over a loop or list comprehension is that you can go back as many times as you want.
Edit
A more compact version using a generator expression instead of a function:
Usage:
Marginally better...
Pandas
is great for time series in general, and has direct support for date ranges.For example
pd.date_range()
:It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in
bdate_range
.See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps
In addition it fully supports pytz timezones and can smoothly span spring/autumn DST shifts.
I know this has been answered, but I'll put down my answer for historical purposes, and since I think it is straight forward.
Sure it won't win anything like code-golf, but I think it is elegant.
You can also use the day ordinal to make it simpler:
Or as suggested in the comments you can create a list like this: