我想将日期范围拆分为较小的日期范围。该函数应获取开始日期,结束日期和切片数,并返回开始日期和结束日期元组列表。
如果我通过(2019-04-01,2019-04-22,5)它应该返回:
(2019-04-18, 2019-04-22)
(2019-04-13, 2019-04-17)
(2019-04-08, 2019-04-12)
(2019-04-03, 2019-04-07)
(2019-04-01, 2019-04-02)
这就是我现在拥有的:
from datetime import date, timedelta
def split_date_range(start_date, end_date, num_of_slices):
interval =(end_date - start_date).days / num_of_slices
for i in range(num_of_slices):
partition_start_date = max(start_date, end_date - timedelta(days=(i + 1) * interval + i))
partition_end_date = partition_start_date + timedelta(days=interval)
yield (partition_start_date, partition_end_date)
if __name__ == '__main__':
start_date = date.today() - timedelta(days=22)
end_date = date.today() - timedelta(days=1)
print(list(split_date_range(start_date, end_date, 5)))
这背后的逻辑是2019-04-01和2019-04-22之间的区别是22天。如果我用22除以5取整至5(4.4)。每个元组的日期范围是5天,其余的天数保留为元组列表中的最后一项。什么是最灵活的实现方法?