【Python】将时间段按照固定天数分割

1.固定时间点(00:00:00-23:59:59)的时间段(2023.1.1-2025.3.31每N天)分割

def run():

    begin_date = datetime(2023, 1, 1)
    end_date = datetime(2025, 3, 31)
    split_days = 7  # 固定天数,比如7天一段

    current_date = begin_date
    while current_date <= end_date:
        current_begin_time = current_date.strftime('%Y-%m-%d') + ' 00:00:00'
        next_date = current_date + timedelta(days=split_days - 1)
        if next_date > end_date:
            next_date = end_date
        current_end_time = next_date.strftime('%Y-%m-%d') + ' 23:59:59'
        print(current_begin_time, current_end_time)
        current_date = next_date + timedelta(days=1)
        
output:
	2023-01-01 00:00:00 2023-01-07 23:59:59
	2023-01-08 00:00:00 2023-01-14 23:59:59
	2023-01-15 00:00:00 2023-01-21 23:59:59
	2023-01-22 00:00:00 2023-01-28 23:59:59
	2023-01-29 00:00:00 2023-02-04 23:59:59
	2023-02-05 00:00:00 2023-02-11 23:59:59
	2023-02-12 00:00:00 2023-02-18 23:59:59
	2023-02-19 00:00:00 2023-02-25 23:59:59
	2023-02-26 00:00:00 2023-03-04 23:59:59
	2023-03-05 00:00:00 2023-03-11 23:59:59
	2023-03-12 00:00:00 2023-03-18 23:59:59
	2023-03-19 00:00:00 2023-03-25 23:59:59

2.指定时间点(6:30:00-9:30:00 16:30:00-19:30:00)的时间段(2023.1.1-2025.3.31每天)分割

def run():
    begin_date = datetime(2023, 1, 1)
    end_date = datetime(2025, 3, 31)
    time_ranges = [('06:30:00', '09:30:00'), ('16:30:00', '19:30:00')]
    current_date = begin_date
    while current_date <= end_date:
        for start_t, end_t in time_ranges:
            current_begin_time = current_date.strftime('%Y-%m-%d') + ' ' + start_t
            current_end_time = current_date.strftime('%Y-%m-%d') + ' ' + end_t
            print(current_begin_time, current_end_time)
            current_date += timedelta(days=1)
            
output:
	2023-01-01 06:30:00 2023-01-01 09:30:00
	2023-01-02 16:30:00 2023-01-02 19:30:00
	2023-01-03 06:30:00 2023-01-03 09:30:00
	2023-01-04 16:30:00 2023-01-04 19:30:00
	2023-01-05 06:30:00 2023-01-05 09:30:00
	2023-01-06 16:30:00 2023-01-06 19:30:00
	2023-01-07 06:30:00 2023-01-07 09:30:00
	2023-01-08 16:30:00 2023-01-08 19:30:00
	2023-01-09 06:30:00 2023-01-09 09:30:00
	2023-01-10 16:30:00 2023-01-10 19:30:00
	2023-01-11 06:30:00 2023-01-11 09:30:00
	2023-01-12 16:30:00 2023-01-12 19:30:00
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值