asado23 asado23 - 1 month ago 13
Python Question

timedelta returning wrong month

I wrote some code to send requests to an API. The API allows the search to be performed between a given set of dates. My code takes a datetime object and increases that object by a timedelta, lets call this timedelta d. I have a second datetime object which increments the by d-1. The idea is to get non overlapping time periods. Everything seems to be working fine except that when the date changes from November the first back to October 31st, the month returned by my date time is incorrect. Here is the code:

start_date=datetime(2013,9,22)
end_date=datetime(2013,12,1)

d = start_date
delta = timedelta(days=10)

while d <= end_date:
ys=d.strftime('%Y')
ms=d.strftime('%m')
ds=d.strftime('%d')
d += delta

ye=d.strftime('%Y')
me=d.strftime('%m')
de=(d-timedelta(days=1)).strftime('%d')
print ys+'-'+ms+'-'+ds+'..'+ye+'-'+me+'-'+de


And here is the output:2013-09-22..2013-10-01

2013-10-02..2013-10-11
2013-10-12..2013-10-21
2013-10-22..2013-11-31 #the second date printed should be 2013-10-31
2013-11-01..2013-11-10
2013-11-11..2013-11-20
2013-11-21..2013-12-30
2013-12-01..2013-12-10


Any idea on why this is happening?

Answer

Try to use d-timedelta(days=1) on all the ye, me and de, not only de

Comments