There is an easy way to clean up your loop:
lastSeven = [endDate]
for x in range(1, 7):
lastSeven.append(endDate - datetime.timedelta(x))
Essentially, I am working backwards instead of forwards. This yields the correct dates, but in backwards order.
If you want them in chronological order do:
lastSeven.sort()
Also, just in case you don't like the sorting thing, here's a version which goes forwards:
lastSeven = [endDate - datetime.timedelta(7)]
for x in range(1, 7):
lastSeven.append(lastSeven[x-1] + dateTime.timeDelta(1))
Lastly, there are some issues with your coding style:
Don't write code like this:
shortName = 3
veryLongName = 4
Write code like this:
shortName = 3
veryLongName = 4
Also, put a space between arguments (so foo(x, y)
is correct, while foo(x,y)
is not).
This is in line with PEP8, the python style guide
Lastly, you can use a list comprehension for a bit of extra speed as one of the answers suggests, but it comes at the cost of readability, which is something that Python strives to maximize over speed (usually).
Here are two below:
# go backwards, then sort
lastSeven = [endDate - datetime.timedelta(x) for x in range(7)].sort()
# go to start, then iterate forwards
startDate = endDate - datetime.timedelta(7-1)
lastSeven = [startDate + datetime.timedelta(x) for x in range(7)]