HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Getting a date range

Submitted by: @import:stackexchange-codereview··
0
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:

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)]

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 = 4
shortName = 3
veryLongName = 4

Context

StackExchange Code Review Q#60061, answer score: 7

Revisions (0)

No revisions yet.