统计和规定时间的交集
统计跨天时间段和夜间时间段(01:00 ~ 06:00)的交集
需求定义
最近写代码遇到一个需求
上网搜了一下,大部分的方案都是给定了具体日期,例如求2022-02-02 05:30 ~ 2022-02-02 06:30和2022-02-02 06:00 ~ 2022-02-02 08:30这两个时间段的交集,而没有忽略日期,单纯考虑%H:%M:%S的交集统计。
解决思路
思路其实也很简单,就是统计每天和01:00 ~ 06:00的交集,例如2022-02-02 05:30 ~ 2022-02-03 06:30,那就是先统计2022-02-02和01:00 ~ 06:00的交集,再统计2022-02-03和01:00 ~ 06:00的交集,最终结果以秒数统计。
解决代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| def timeIntersection(time2JudgeStart,time2JudgeEnd,ruleHourStart,ruleHourEnd): ''' Parameters: time2JudgeStart - 用户时间段开始时间 - string '%Y-%m-%d %H:%M:%S' time2JudgeEnd - 用户时间段停止时间 - string '%Y-%m-%d %H:%M:%S' ruleHourStart - 求交集的规定开始时间(小时) - int ruleHourStart - 求交集的规定停止时间(小时) - int
Returns: intersectionSum - 交集统计时间(秒) - int
''' time2JudgeStart = datetime.strptime(time2JudgeStart, '%Y-%m-%d %H:%M:%S') time2JudgeEnd = datetime.strptime(time2JudgeEnd, '%Y-%m-%d %H:%M:%S') startDay = time2JudgeStart.date() endDay = time2JudgeEnd.date() diffDays = (endDay - startDay).days intersectionSum = 0 for i in range(diffDays+1): timeDay = startDay+timedelta(days=i) timeStart = datetime(timeDay.year, timeDay.month, timeDay.day, ruleHourStart, 0) timeEnd = datetime(timeDay.year, timeDay.month, timeDay.day, ruleHourEnd, 0) if(time2JudgeEnd <= timeStart):break if(time2JudgeStart >= timeEnd):continue if(time2JudgeEnd < timeEnd): if(time2JudgeStart < timeStart):intersectionSum = intersectionSum + (time2JudgeEnd-timeStart).total_seconds() else:intersectionSum = intersectionSum + (time2JudgeEnd-time2JudgeStart).total_seconds() if(time2JudgeEnd > timeEnd): if(time2JudgeStart < timeStart):intersectionSum = intersectionSum + (timeEnd-timeStart).total_seconds() else:intersectionSum = intersectionSum + (timeEnd-time2JudgeStart).total_seconds() return intersectionSum
|