Python Generating A List Of Dates Between Two Dates
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: fr
Solution 1:
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:
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:
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:
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:
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
Post a Comment for "Python Generating A List Of Dates Between Two Dates"