Search code examples
pythondatedatetimepython-datetime

Pythonic way to get all dates within time period


What specific syntax must be changed in the pseudocode below in order for the getDatesList(startDate,endDate) function to return a list of every valid date including and between any arbitrary startDate and endDate values?

The resulting function should handle all calculations of dates in the most Pythonic way possible, thus minimizing the chance of errors being mixed in as this code is managed over time. This includes leapdays as you see in the example below, but it should also include other things such as automatically knowing the number of days in any month without needing to be told.

Pseudocode:

from datetime import date

def getDatesList(startDate,endDate):  
  startDateParts = startDate.split('-')
  yearNum = int(startDateParts[0])
  monthNum = int(startDateParts[1])
  dayNum = int(startDateParts[2])
  startDateObj = date(yearNum,monthNum,dayNum)
  endDateParts = endDate.split('-')
  endYearNum = int(endDateParts[0])
  endMonthNum = int(endDateParts[1])
  endDayNum = int(endDateParts[2])
  endDateObj = date(endYearNum,endMonthNum,endDayNum)
  datesList = []  
  dateObj = date(yearNum,monthNum,dayNum)
  while dateObj<endDateObj:
    datesList.append(dateObj)
    dateObj+=1day
  return datesList

listOfDates = getDatesList('2020-02-27','2020-03-02')
for eachDate in listOfDates:
  print(eachDate)

The results of running the above code should be a list of all days between the start and end days, which for the above sample inputs would be:

2020-02-27
2020-02-28
2020-02-29
2020-03-02
2020-03-03

Notice the leap day 2020-02-29 in the results above.

But the resulting function should run equally cleanly if given any two arbitrary dates as inputs, for example '1986-02-11' through '2018-09-27'.


Solution

  • You can use timedelta to do this , here is the snippet

    from datetime import datetime, timedelta
    
    def date_range(start, end):
        start_date = datetime.strptime(start, '%Y-%m-%d').date()
        end_date = datetime.strptime(end, '%Y-%m-%d').date()
        delta = end_date - start_date 
        days = [start_date + timedelta(days=i) for i in range(delta.days + 1)]
        return list(map(lambda n: n.strftime("%Y-%m-%d"), days))
    
    
    print(date_range('2020-02-27', '2020-03-02'))