2

I have a start date of datetime(2015, 01, 01) and I want my program to advance to the first of the following month with each step, it will be doing this for a couple of decades, but to troubleshoot it is just doing it for one year. The reason it is in a while loop is because I also want it to some scrapping based on the month and year. This is my code that I have written:

import datetime

dayS = 01; monthS = 01; yearS = 2015 #Start date
dayE = 01; monthE = 01; yearE = 2016 #End date
SDate = datetime.date(yearS, monthS, dayS)
EDate = datetime.date(yearE, monthE, dayE)
Date = []

while SDate <= EDate:
        Date.append(SDate.strftime('%d/%m/%Y'))
        if SDate.strftime('%m') == '02':
                step = datetime.timedelta(days=28)
        if SDate.strftime('%m') == '09' or '04' or '06' or '11':
                step = datetime.timedelta(days=30)
        if SDate.strftime('%m') == '01' or '03' or '05' or '07' or '08' or '10' or '12':
                step = datetime.timedelta(days=31)
        SDate += step

print Date

But the result I got is ['01/01/2015', '01/02/2015', '04/03/2015', '04/04/2015', '05/05/2015', '05/06/2015', '06/07/2015', '06/08/2015', '06/09/2015', '07/10/2015', '07/11/2015', '08/12/2015'], and as you can see for some months it doesn't add the correct amount of days.

Any help is much appreciated!

Tazza2092
  • 51
  • 1
  • 8
  • mgilson has correctly identified the problem with the above code, but I'd rework it a bit to do less of the work yourself. Given an arbitrary date, `(somedate.replace(day=1) + datetime.timedelta(days=31)).replace(day=1)` is always the first day of the next month. If you know you only start from the first of the month, you can skip the first `replace`. Or there are third-party libraries like `dateutil` that can help. – Peter DeGlopper Oct 03 '14 at 19:46

1 Answers1

4

What you have is the classic "or" problem.

"foo" == "1" or "2"

will always return True because it gets parsed as:

("foo" == "1") or "2"
         |         |
         False or "2"
               |
              "2"

Note that in this case, you might be better off using datetime.date.replace.

while SDate <= EDate:
    if SDate.month < 12:
        SDate = SDate.replace(month=SDate.month + 1)
    else:
        SDate = SDate.replace(month=1, year=SDate.year + 1)
mgilson
  • 300,191
  • 65
  • 633
  • 696