6
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review! I hope you get some helpful answer. \$\endgroup\$ – SirPython Jan 31 '16 at 0:26
8
\$\begingroup\$

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)
    ]
\$\endgroup\$
  • 1
    \$\begingroup\$ Outstanding. I like the middle example the best. \$\endgroup\$ – caseym Jan 30 '16 at 23:45
  • 2
    \$\begingroup\$ The final simplification is just yielding the dates instead of building an array. \$\endgroup\$ – Caridorc Jan 31 '16 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.