Python generating a list of dates between two dates

PythonPandasDataframe

Python Problem Overview


I want to generate a list of dates between two dates and store them in a list in string format. This list is useful to compare with other dates I have.

My code is given below:

from datetime import date, timedelta

sdate = date(2019,3,22)   # start date
edate = date(2019,4,9)   # end date

def dates_bwn_twodates(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)
print(dates_bwn_twodates(sdate,edate))

My present output:

<generator object dates_bwn_twodates at 0x000002A8E7929410>

My expected output:

['2019-03-22',.....,'2019-04-08']

Something wrong in my code.

Python Solutions


Solution 1 - Python

You can use pandas.date_range() for this:

import pandas
pandas.date_range(sdate,edate-timedelta(days=1),freq='d')

DatetimeIndex(['2019-03-22', '2019-03-23', '2019-03-24', '2019-03-25',
           '2019-03-26', '2019-03-27', '2019-03-28', '2019-03-29',
           '2019-03-30', '2019-03-31', '2019-04-01', '2019-04-02',
           '2019-04-03', '2019-04-04', '2019-04-05', '2019-04-06',
           '2019-04-07', '2019-04-08'],
          dtype='datetime64[ns]', freq='D')

Solution 2 - Python

Your code rewritten as a list comprehension:

[sdate+timedelta(days=x) for x in range((edate-sdate).days)]

results:

[datetime.date(2019, 3, 22),
 datetime.date(2019, 3, 23),
 datetime.date(2019, 3, 24),
          :
 datetime.date(2019, 4, 7),
 datetime.date(2019, 4, 8)]

Solution 3 - Python

You'd need to turn it into a list with strings explicitly:

print([str(d) for d in dates_bwn_twodates(sdate,edate)])

Solution 4 - Python

from datetime import date, timedelta

sdate = date(2019,3,22)   # start date
edate = date(2019,4,9)   # end date
date_modified=sdate
list=[sdate] 


while date_modified<edate:
    date_modified+=timedelta(days=nbDaysbtw2dates) 
    list.append(date_modified)

print(list) 

Solution 5 - Python

I'm surprised this isn't a standard function in datetime package.

Here's a function that does what is requested:

from datetime import timedelta

def date_range_list(start_date, end_date):
    # Return list of datetime.date objects between start_date and end_date (inclusive).
    date_list = []
    curr_date = start_date
    while curr_date <= end_date:
        date_list.append(curr_date)
        curr_date += timedelta(days=1)
    return date_list

Usage:

from datetime import date, timedelta

def date_range_list(start_date, end_date):
    # Return list of datetime.date objects between start_date and end_date (inclusive).
    date_list = []
    curr_date = start_date
    while curr_date <= end_date:
        date_list.append(curr_date)
        curr_date += timedelta(days=1)
    return date_list

start_date = datetime.date(year=2021, month=12, day=20)
stop_date = datetime.date(year=2021, month=12, day=25)
date_list = date_range_list(start_date, stop_date)

date_list

Output:

[datetime.date(2021, 12, 20),
 datetime.date(2021, 12, 21),
 datetime.date(2021, 12, 22),
 datetime.date(2021, 12, 23),
 datetime.date(2021, 12, 24),
 datetime.date(2021, 12, 25)]

Solution 6 - Python

There is a much simpler approach and can be used by just modifying your code. It is as follows;

from datetime import datetime, timedelta
from datetime import date


def date_bwn_two_dates(start_date, end_date):
    date_list = [] # The list where we want to store
    for i in range(int((end_date-start_date).days)+1): # Iterate between the range of dates
        year = (start_date+timedelta(i)).strftime("%Y") # Get the Year
        month = (start_date+timedelta(i)).strftime("%m") # Get the month
        date_a = (start_date+timedelta(i)).strftime("%d") # Get the day
        date_list.append([year, month, date_a]) # Append the Objects accquired
    return date_list # return the list


for i in date_bwn_two_dates(date(2020, 12, 1), date(2021, 12, 1)):
    print(i)

Solution 7 - Python

You can use the moment library from https://github.com/zachwill/moment.git to make your life easier.

import moment

def dates_bwn_twodates(start_date, end_date):
    diff = abs(start_date.diff(end_date).days)
    
    for n in range(0,diff+1):
        yield start_date.strftime("%Y-%m-%d")
        start_date = (start_date).add(days=1)

sdate = moment.date('2019-03-22')   #start date
edate = moment.date('2019-04-09')   #end date  

and then you have options

dates = list(dates_bwn_twodates(sdate,edate)) #dates as a list

or you can iterate

for date in dates_bwn_twodates(sdate,edate):
    #do something with each date

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMainlandView Question on Stackoverflow
Solution 1 - PythonankyView Answer on Stackoverflow
Solution 2 - Pythonglenn15View Answer on Stackoverflow
Solution 3 - PythonSimeon VisserView Answer on Stackoverflow
Solution 4 - PythonRenaudView Answer on Stackoverflow
Solution 5 - PythonJagerber48View Answer on Stackoverflow
Solution 6 - PythonishaantView Answer on Stackoverflow
Solution 7 - PythondarkisView Answer on Stackoverflow