根据给定的开始时间、结束时间和时间间隔,生成一系列时间周期,每个时间周期由开始时间和结束时间组成,这些时间周期可以用于在特定时间段内进行按一定间隔的任务划分或数据处。
时间区间的切分,可以用于循环获取数据;
from datetime import datetime, timedelta
def time_periods(begin_time, end_time, interval):
t1 = datetime.strptime(begin_time, '%Y-%m-%d %H:%M:%S')
t2 = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
days = (t2 - t1).days
periods = []
for i in range(0, days + 1, interval): # days+1, 非常关键
period_start = t1 + timedelta(days=i)
period_end = min(period_start + timedelta(days=interval), t2)
periods.append((period_start, period_end))
return periods
if __name__ == '__main__':
begin_time = '2024-08-01 08:00:00'
end_time = '2024-09-01 07:59:59'
interval =8 # 自定义间隔区间
periods = time_periods(begin_time, end_time, interval)
验证:
begin_time = '2024-08-01 08:00:00'
end_time = '2024-09-01 07:59:59'
interval =3 # 自定义间隔区间
t1 = datetime.strptime(begin_time, '%Y-%m-%d %H:%M:%S')
t2 = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
days = (t2 - t1).days
print(days)
periods = []
for i in range(0, days + 1, interval): # days+1, 非常关键
period_start = t1 + timedelta(days=i)
period_end = min(period_start + timedelta(days=interval), t2)
print('i:',i, ' period_start:',period_start, ' period_end:',period_start + timedelta(days=interval), ' 结束修正:',period_end )
# -------------------------------------- 输出 ----------------------------------------------------
30
i: 0 period_start: 2024-08-01 08:00:00 period_end: 2024-08-04 08:00:00 结束修正: 2024-08-04 08:00:00
i: 3 period_start: 2024-08-04 08:00:00 period_end: 2024-08-07 08:00:00 结束修正: 2024-08-07 08:00:00
i: 6 period_start: 2024-08-07 08:00:00 period_end: 2024-08-10 08:00:00 结束修正: 2024-08-10 08:00:00
i: 9 period_start: 2024-08-10 08:00:00 period_end: 2024-08-13 08:00:00 结束修正: 2024-08-13 08:00:00
i: 12 period_start: 2024-08-13 08:00:00 period_end: 2024-08-16 08:00:00 结束修正: 2024-08-16 08:00:00
i: 15 period_start: 2024-08-16 08:00:00 period_end: 2024-08-19 08:00:00 结束修正: 2024-08-19 08:00:00
i: 18 period_start: 2024-08-19 08:00:00 period_end: 2024-08-22 08:00:00 结束修正: 2024-08-22 08:00:00
i: 21 period_start: 2024-08-22 08:00:00 period_end: 2024-08-25 08:00:00 结束修正: 2024-08-25 08:00:00
i: 24 period_start: 2024-08-25 08:00:00 period_end: 2024-08-28 08:00:00 结束修正: 2024-08-28 08:00:00
i: 27 period_start: 2024-08-28 08:00:00 period_end: 2024-08-31 08:00:00 结束修正: 2024-08-31 08:00:00
i: 30 period_start: 2024-08-31 08:00:00 period_end: 2024-09-03 08:00:00 结束修正: 2024-09-01 07:59:59