如何判断采样频率触发时是否需跨日?(避免面条代码)
解决采样时间跨日自动处理的简洁方案
不用手动写一堆条件判断跨日,直接利用语言自带的日期时间运算工具就能搞定,核心思路是:把起始时间转换成带日期的时间对象,每次采样时间直接在上一次的基础上加设定的频率小时,日期时间库会自动处理跨日(甚至跨月跨年)的情况,最后再格式化成你需要的字符串格式。
具体步骤
- 将用户输入的起始小时与基准日期(比如当日)结合,生成完整的起始时间对象
- 循环生成采样时间:每次取当前时间对象,格式化后存入结果,再给当前时间对象加上频率小时
- 所有跨日逻辑由日期时间库自动处理,无需手动判断
示例代码(Python)
from datetime import datetime, timedelta # 用户配置参数 frequency_hours = 3 start_hour = 20 sample_count = 4 # 对应示例2的4次采样 # 构建起始时间对象(基准日期用当日,可按需调整) start_datetime = datetime.now().replace(hour=start_hour, minute=0, second=0, microsecond=0) sample_times = [] current_dt = start_datetime for _ in range(sample_count): # 格式化为要求的UTC格式 sample_str = current_dt.strftime("%Y-%m-%dT%H:00:00Z") sample_times.append(sample_str) # 累加频率小时,自动处理跨日 current_dt += timedelta(hours=frequency_hours) print(sample_times) # 输出示例: # ['2024-05-20T20:00:00Z', '2024-05-20T23:00:00Z', '2024-05-21T02:00:00Z', '2024-05-21T05:00:00Z']
示例代码(JavaScript)
// 用户配置参数 const frequencyHours = 3; const startHour = 20; const sampleCount = 4; // 构建起始时间对象 const startDate = new Date(); startDate.setHours(startHour, 0, 0, 0); const sampleTimes = []; let currentDate = new Date(startDate); for (let i = 0; i < sampleCount; i++) { // 格式化为UTC标准格式 const year = currentDate.getUTCFullYear(); const month = String(currentDate.getUTCMonth() + 1).padStart(2, '0'); const day = String(currentDate.getUTCDate()).padStart(2, '0'); const hour = String(currentDate.getUTCHours()).padStart(2, '0'); const sampleStr = `${year}-${month}-${day}T${hour}:00:00Z`; sampleTimes.push(sampleStr); // 累加频率小时,自动处理跨日 currentDate.setHours(currentDate.getHours() + frequencyHours); } console.log(sampleTimes);
方案优势
- 彻底规避手动判断小时边界的复杂逻辑,代码简洁易维护
- 日期时间库自动处理所有边界场景(比如23:00加3小时到次日02:00、月末加天数到次月等)
- 适配1-8小时的所有频率设定,无论第几次采样跨日都能正确生成时间
内容的提问来源于stack exchange,提问作者PeterK
相关产品推荐
相关产品推荐

