emma perkins emma perkins - 4 months ago 14
Python Question

Python - looping through dates not working

Imtrying to loop through date ranges using this below code but for some reason the code stops when hititng the while statment. I dont get any error

startDate = datetime.date( 2016, 7, 13 )
endDate = datetime.date( 2010, 1, 1 )
dayDelta = datetime.timedelta( days=1 )

while startDate < endDate:

browser.get("http://www.racingpost.com/horses2/results/home.sd?r_date=" + startDate.strftime("%Y-%m-%d"))
tree2 = html.fromstring(browser.page_source)
startDate += dayDelta

Answer

The reason is, that "startDate < (less than) endDate" is in your case not TRUE.

For the interpreter your code is therefore not wrong, because he can't tell you if this while should be the case or not and that's why you won't get an error message.

You can try such things with a simple check with print (sometimes faster than a debugger and my favourit to check for quick errors)

import datetime

startDate = datetime.date( 2016, 7, 13 )
endDate = datetime.date( 2010, 1, 1 )
dayDelta = datetime.timedelta( days=1 )

'''
while startDate < endDate:
    print 'test' #no output
'''
while startDate > endDate:
    print 'test' #infinite loop, lot of output