簡體   English   中英

將 2 個給定日期之間的天數拆分為特定的批量大小,並相應地獲取 start 和 end_date

[英]Split days between 2 given dates into specific batch size and get the start and end_date accordingly

我想將 2 個給定日期之間的天數拆分為特定的批量大小,以使我的 api 調用變得容易。 我目前正在使用它來每月拆分它。 但是,需要根據用戶輸入的批量大小進一步拆分它並獲取 start 和 end_date。

例如:

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

我正在這樣做:我應該做出哪些改變?

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 已經能夠像數字一樣計算日期。 在日期時間中使用可用的 function。

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 ()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM