snippetpythonMinor
Create array of date pairs for next 10 days
Viewed 0 times
createarraydatenextforpairsdays
Problem
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 datesSolution
Rather that continuing to append to arrive, just use the
You can also use call
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:
For here its a simple step to making it a list comprehension:
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 datesIf 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 datesFor 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)
]Code Snippets
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 datesdef 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 datesdef 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)
]Context
StackExchange Code Review Q#118402, answer score: 8
Revisions (0)
No revisions yet.