I want to split the days between 2 given dates into a specific batch size to make my api call easy. I am currently using this to split it on a monthly basis. However, need to split it further depending on user input batch size and get the start and end_date.
For eg:
start_date : 2020-01-01
end_date : 2020-01-31
batch: 10
Output:
start: 2020-01-01
end :2020-01-10
start : 2020-01-11
end: 2020-01-20
start : 2020-01-21
end: 2020-01-30
start: 2020-01-31
end: 2020-01-31
I am doing this: what changes should I make?
from dateutil import rrule, parser
start = parser.parse('Jan 21 2020')
end = parser.parse('Oct 30 2020')
date_list = [start]
date_list.extend(list(rrule.rrule(rrule.MONTHLY, bymonthday=(-1,1), dtstart=start, until=end)))
date_list.append(end)
print(date_list)
You can use the datetime and timedelta option to get the batches. You don't need to load dateutil and do complex manipulation. datetime already has the ability to compute dates like numbers. Use the available function in datetime.
import datetime
start_date = '2020-01-01'
end_date = '2020-01-31'
batch = 10
#First convert the string version of start and end dates into datetime
start = datetime.datetime.strptime(start_date, '%Y-%m-%d')
end = datetime.datetime.strptime(end_date, '%Y-%m-%d')
#then set the timedelta to the batch - 1 day
#end date is always calculated as 9 more days not 10 (hence -1)
step = datetime.timedelta(days=(batch-1))
#iterate through the loop until start <= end
while start <= end:
print ('Start :', start.date()) #print start date
start += step #add the timedelta to start
if start > end: start = end
print ('End :', start.date()) #print end date
start += datetime.timedelta(days=1) #now increment by 1 more to get start date
print ()
The output of this will be:
Start : 2020-01-01
End : 2020-01-10
Start : 2020-01-11
End : 2020-01-20
Start : 2020-01-21
End : 2020-01-30
Start : 2020-01-31
End : 2020-01-31
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.