Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
    
Welcome to Code Review! I hope you get some helpful answer. – SirPython Jan 31 at 0:26
up vote 7 down vote accepted

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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