I need to query an API for data over a multi-month period. However, the API chokes on longer than 3-day intervals.
So I want to create a generator function to separate my multi-month date range into 3 day segments that I can use while repeatedly calling my function that hits the API: When I pass it the start date and end date, it gives me:
- the first time gives me start date,start date +3 days
- next time gives me start date + 3 days, start date + 6 days
- each time thereafter it moves forward by 3 day increments
- until it hits the end date, when it gives me the days remaining to hit the end date if I still have 1 or 2 days left of data to grab
- stops
Here's my code so far. It will work for the first time, but I'm not sure how to get the start date to increment by 3 days the next time I call the function. And I'm also not sure how if I still have 1 or 2 days left before hitting the final end date to set my until
variable to the final end date--I think right now it simply says "there's less than 3 days left until the final date, so let's quit":
3_day_segmenter(start, end):
start_date = datetime.strptime(start, '%Y-%m-%d')
end_date = datetime.strptime(end, '%Y-%m-%d')
since = start_date
for date in range(int ((end_date - start_date).days)):
until = start_date + datetime.timedelta(days=3)
yield since, until