patternpythonMinor
Getting a date range
Viewed 0 times
rangegettingdate
Problem
I'm just trying to be more pythonic in my coding style and was wondering if this is a good way to get a list of seven days leading up to and including
endDate:daysDelta = 6
lastSeven = [endDate - datetime.timedelta(days=daysDelta)]
for x in range(1,7):
myOffset = daysDelta - x
lastSeven.append(endDate - datetime.timedelta(days=myOffset))Solution
There is an easy way to clean up your loop:
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:
Also, just in case you don't like the sorting thing, here's a version which goes forwards:
Lastly, there are some issues with your coding style:
Don't write code like this:
Write code like this:
Also, put a space between arguments (so
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:
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 = 4Write code like this:
shortName = 3
veryLongName = 4Also, 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)]Code Snippets
lastSeven = [endDate]
for x in range(1, 7):
lastSeven.append(endDate - datetime.timedelta(x))lastSeven.sort()lastSeven = [endDate - datetime.timedelta(7)]
for x in range(1, 7):
lastSeven.append(lastSeven[x-1] + dateTime.timeDelta(1))shortName = 3
veryLongName = 4shortName = 3
veryLongName = 4Context
StackExchange Code Review Q#60061, answer score: 7
Revisions (0)
No revisions yet.