Python generating a list of dates between two dates
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)]
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)]
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)
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')