# Create array of date pairs for next 10 days

I wrote the below function which successfully creates pairs of dates in the format I need. However, I'm fairly new to Python and feel there must be a way to make this easier to read. Can this code be improved?

def getNextTenDays():
dates = []
arrive = datetime.datetime.now()
for n in range(1, 11):
arrive += datetime.timedelta(days=1)
next_day = arrive + datetime.timedelta(days=1)
arrive_s = datetime.datetime.strftime(arrive, '%m/%d/%Y')
next_day_s = datetime.datetime.strftime(next_day, '%m/%d/%Y')
dates.append({'arrive': arrive_s, 'depart': next_day_s})
return dates

• Welcome to Code Review! I hope you get some helpful answer. – SirPython Jan 31 '16 at 0:26

Rather that continuing to append to arrive, just use the n offset from 'today'.

You can also use call strftime from a datetime object directly, like so:

def getNextTenDays():
dates = []
today = datetime.datetime.now()
for n in range(1, 11):
arrive = today + datetime.timedelta(days=n)
next_day = today + datetime.timedelta(days=n+1)
arrive_s = arrive.strftime('%m/%d/%Y')
next_day_s = next_day.strftime('%m/%d/%Y')
dates.append({'arrive': arrive_s, 'depart': next_day_s})
return dates


If you are just going to return the strings, and throw away the actual date times you can do that in one go like so:

def getNextTenDays():
dates = []
today = datetime.datetime.now()
for n in range(1, 11):
dates.append({
'arrive': (today + datetime.timedelta(days=n)).strftime('%m/%d/%Y'),
'depart': (today + datetime.timedelta(days=n+1)).strftime('%m/%d/%Y'),
})
return dates


For here its a simple step to making it a list comprehension:

def getNextTenDays():
today = datetime.datetime.now()
return [
{
'arrive': (today + datetime.timedelta(days=n)).strftime('%m/%d/%Y'),
'depart': (today + datetime.timedelta(days=n+1)).strftime('%m/%d/%Y'),
}
for n in range(1,11)
]

• Outstanding. I like the middle example the best. – caseym Jan 30 '16 at 23:45
• The final simplification is just yielding the dates instead of building an array. – Caridorc Jan 31 '16 at 12:00