发布于 

统计和规定时间的交集

统计跨天时间段和夜间时间段(01:00 ~ 06:00)的交集

需求定义

最近写代码遇到一个需求

夜间停留时间统计

用户的时间段是%Y-%m-%d %H:%M:%S形式,需要统计这段时间和01:00 ~ 06:00的交集,即,假设用户时间段是2022-02-02 05:30 ~ 2022-02-02 06:30,那么交集即为30min。如果用户时间段是2022-02-02 05:30 ~ 2022-02-03 06:30,那么交集即为5h30min。

上网搜了一下,大部分的方案都是给定了具体日期,例如求2022-02-02 05:30 ~ 2022-02-02 06:302022-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-0201:00 ~ 06:00的交集,再统计2022-02-0301: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