Creating a range of dates in Python

Thomas Browne picture Thomas Browne · Jun 14, 2009 · Viewed 488.8k times · Source

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

Answer

S.Lott picture S.Lott · Jun 14, 2009

Marginally better...

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