如何在两个非整点Datetime之间生成符合要求的小时时间槽?
问题描述
我查了很多关于如何在两个日期之间生成小时级时间槽的帖子,但我的场景是两个非整点开始/结束的时间,示例如下:
开始时间 = 2023-04-20 06:30:00 结束时间 = 2023-04-20 14:30:00
我期望得到如下格式的输出:
小时 开始时间 结束时间 6 2023-04-20 06:30:00 2023-04-20 07:00:00 -- *不要从6:00开始* 7 2023-04-20 07:00:00 2023-04-20 08:00:00 ... 13 2023-04-20 13:00:00 2023-04-20 14:00:00 14 2023-04-20 14:00:00 2023-04-20 14:30:00 -- *不要到15:00结束*
解决方案(Python示例)
可以用datetime模块实现需求,核心思路是分三段处理:起始非整点段、中间完整小时段、结束非整点段,确保边界时间完全匹配你的要求。
代码实现:
from datetime import datetime, timedelta def generate_time_slots(start_str, end_str): # 解析输入的时间字符串 start = datetime.strptime(start_str, "%Y-%m-%d %H:%M:%S") end = datetime.strptime(end_str, "%Y-%m-%d %H:%M:%S") slots = [] # 处理第一个非整点时间段 next_hour = start.replace(minute=0, second=0) + timedelta(hours=1) if next_hour <= end: slots.append((start.hour, start, next_hour)) current_time = next_hour else: # 开始和结束在同一个小时内的情况 slots.append((start.hour, start, end)) return slots # 遍历生成中间的完整小时段 while current_time + timedelta(hours=1) <= end: next_slot_end = current_time + timedelta(hours=1) slots.append((current_time.hour, current_time, next_slot_end)) current_time = next_slot_end # 处理最后一个非整点时间段 if current_time < end: slots.append((current_time.hour, current_time, end)) # 按要求格式输出 print("小时 开始时间 结束时间") for hour, slot_start, slot_end in slots: note = "" if hour == start.hour: note = " -- *不要从{}:00开始*".format(start.hour) elif hour == end.hour: note = " -- *不要到{}:00结束*".format(end.hour + 1) print(f"{hour:<5} {slot_start.strftime('%Y-%m-%d %H:%M:%S')} {slot_end.strftime('%Y-%m-%d %H:%M:%S')}{note}") # 测试示例 generate_time_slots("2023-04-20 06:30:00", "2023-04-20 14:30:00")
运行这段代码后,会输出你期望的时间槽格式,不管起始/结束时间是不是整点,都能精准生成对应时段。
内容的提问来源于stack exchange,提问作者Kevin Marchand
相关产品推荐
相关产品推荐

