내 API 호출을 쉽게하기 위해 주어진 2 개의 날짜 사이의 날짜를 특정 배치 크기로 나누고 싶습니다. 나는 현재 이것을 매월 분할하기 위해 사용하고 있습니다. 그러나 사용자 입력 배치 크기에 따라 더 분할하고 시작 및 종료 날짜를 가져와야합니다.
예 :
start_date : 2020-01-01
end_date : 2020-01-31
batch: 10
산출:
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
나는 이것을하고있다 : 나는 무엇을 변경해야 하는가?
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)
datetime 및 timedelta 옵션을 사용하여 배치를 가져올 수 있습니다. dateutil을로드하고 복잡한 조작을 할 필요가 없습니다. datetime에는 이미 숫자와 같은 날짜를 계산하는 기능이 있습니다. 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 ()
이 결과는 다음과 같습니다.
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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다