Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 972
Mainland Avatar asked Jan 23 '20 16:01

Mainland


People also ask

How can I get a list of dates between two dates?

We can get the dates between two dates with single method call using the dedicated datesUntil method of a LocalDate class. The datesUntill returns the sequentially ordered Stream of dates starting from the date object whose method is called to the date given as method argument.

How do I create a date range in pandas?

Specifying the valuesSpecify start and end, with the default daily frequency. Specify start and periods, the number of periods (days). Specify end and periods, the number of periods (days). Specify start, end, and periods; the frequency is generated automatically (linearly spaced).


2 Answers

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') 
like image 121
anky Avatar answered Sep 20 '22 01:09

anky


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)] 
like image 42
glenn15 Avatar answered Sep 19 '22 01:09

glenn15