-1

I am trying to print list of dates between two dates but I keep getting error. Below is my code can you please help me figure this out.

#!/usr/bin/python
import sys
from datetime import date, timedelta as td

d1 = date(2016-02-04)
d2 = date(2016-02-06)

delta = d2 - d1

for i in range(delta.days + 1):
    print d1 + td(days=i)
jfs
  • 399,953
  • 195
  • 994
  • 1,670
user1570210
  • 1,169
  • 12
  • 26
  • 37
  • 1
    When posting questions like this, it's important to specify exactly what error you're getting and on what line it is occuring — or better yet, the full traceback that was printed. – martineau May 04 '16 at 18:52

4 Answers4

0

See Print all day-dates between two dates

Also, date() takes three arguments, the day, month and year.

Code:

from datetime import date, timedelta as td

d1 = date(2008, 8, 15)
d2 = date(2008, 9, 15)

delta = d2 - d1

for i in range(delta.days + 1):
    print d1 + td(days=i)
Community
  • 1
  • 1
MattCorr
  • 371
  • 3
  • 11
0

Addressing the error first, you are defining dates like this:

date(2016-02-04)

However the proper syntax is:

#date(Year, Month, Day)
date(2016, 2, 6)

Now for the days in range question:

from datetime import date, timedelta

d1 = date(2016, 2, 4)
d2 = date(2016, 2, 6)
delta = (d2 - d1).days

days = [d1 + timedelta(days=days_to_add) for days_to_add in range(0, delta+1)]
print days

The above outputs:

[datetime.date(2016, 2, 4), datetime.date(2016, 2, 5), datetime.date(2016, 2, 6)]

Note that the solution provided assumes you want to include both the start and end date. If you intended differrently alter the range function.

Also if you would like to print it out in the format you provided you could use the strftime method

for day in days:
    print day.strftime("%Y-%m-%d")

Outputs:

2016-02-04
2016-02-05
2016-02-06
Copy and Paste
  • 496
  • 6
  • 16
0

Here is the solution

#!/usr/bin/python
import sys
from datetime import timedelta, date, datetime

def daterange(start_date, end_date):
   for n in   range((end_date - start_date).days):
        yield start_date + timedelta(n) 


d1= str(sys.argv[1]) #start date in YYYY-MM-DD
d2= str(sys.argv[2]) #end   date in YYYY-MM-DD

start_date = datetime.strptime(d1, "%Y-%m-%d")
end_date  = datetime.strptime(d2, "%Y-%m-%d")

for single_date in daterange(start_date, end_date):
    input1 = single_date.strftime("%Y-%m-%d")
    print input1
user1570210
  • 1,169
  • 12
  • 26
  • 37
-1

As MattCorr said, the only change you need to make is that date() takes three arguments, and you need to format days/months properly ('2' instead of '02' for the example you provided).

EDIT:

The edits I suggest are added here.

from datetime import date, timedelta as td
d1 = date(2016, 2, 4)
d2 = date(2016, 2, 6)

delta = d2 - d1

for i in range(delta.days + 1):
    print(d1 + td(days=i))

Output:

2016-02-04
2016-02-05
2016-02-06