asado23
asado23

Reputation: 467

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?

Upvotes: 0

Views: 422

Answers (2)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

after you have executed:

d += delta

then d represents the start date of the next interval, in one case in your data that is 2013-11-01 so when you get the year and month of that data you get 2013-11 and then get the date of one day before which is 2013-10-31 so it gets 31 instead get all three fields from one day before:

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

or much more concisely you can use strftime('%Y-%m-%d') to get all three fields at once.

start_str = d.strftime("%Y-%m-%d")
d += delta

end_str = (d-timedelta(days=1)).strftime("%Y-%m-%d")
print(start_str+'..'+end_str)

or even more concisely then that:

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

d = start_date
delta = timedelta(days=10)

interval = delta - timedelta(days=1) #the difference between the start of an interval and the last day

while d <= end_date:
    end = d+interval #last day of interval
    print("{:%Y-%m-%d}...{:%Y-%m-%d}".format(d, end))
    d = end + timedelta(days=1) #set d to one day more then the end of interval

Upvotes: 1

Cassum
Cassum

Reputation: 329

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

Upvotes: 0

Related Questions