Requirement: I have to pass start_date and end_date to API and loop b/w range of dates
Example : Range of dates is start_date = '2022-05-23'
and end_date ='2022-05-26'
So When I loop data from API, it should first start_date and end_date as below
start_date = '2022-05-23' and end_date ='2022-05-24'
start_date = '2022-05-24' and end_date ='2022-05-25'
start_date = '2022-05-25' and end_date ='2022-05-26'
start_date = '2022-05-26' and end_date ='2022-05-27'
start_date = '2022-05-27' and end_date ='2022-05-28'
start_date = '2022-05-28' and end_date ='2022-05-29'
Tried as below , was able to increment start_date , not sure how to increment end_date by 1 day of start_date
from datetime import datetime, timedelta
start_date = "2022-05-24"
end_date = "2022-05-29"
start_dt = datetime.strptime(start_date, "%Y-%m-%d")
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
delta = timedelta(days=1)
while start_dt <= end_dt:
print(f"start_dt:{start_dt}")
print(f"end_dt:{end_dt}")
start_dt = delta
CodePudding user response:
[...] not sure how to increment end_date by 1 day of start_date
temp_dt = start_dt datetime.timedelta(days=1)
print(f"start_dt:{start_dt}")
print(f"end_dt:{temp_dt}")
This should work fine.
CodePudding user response:
from datetime import datetime, timedelta
from datetime import date
start_date = "2022-05-24"
end_date = "2022-05-29"
start_dt = datetime.strptime(start_date, "%Y-%m-%d")
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
gap=(end_dt-start_dt).days
print(gap)
end_dt=end_dt- timedelta(gap-1)
delta = timedelta(days=1)
for i in range(gap):
print(f"start_dt:{start_dt}")
print(f"end_dt:{end_dt}")
start_dt = delta
end_dt = delta