import time
# 输入的开始时间和结束时间
# start = "2020-01-03 10:00:00"
# end = "2020-01-03 13:30:00"
# start = "2020-01-03 12:00:00"
# end = "2020-01-03 13:30:00"
#
# start = "2020-01-03 12:10:00"
# end = "2020-01-03 13:00:00"
#
start = "2020-01-03 13:00:00"
end = "2020-01-03 18:00:00"
# 单个时间段过滤
# 要过滤出的时间段
standard_start = "2020-01-03 12:00:00"
standard_end = "2020-01-03 13:30:00"
# 将时间转换为时间戳方便下面 if 语句使用比较
startTimeStamp = int(time.mktime(time.strptime(start, "%Y-%m-%d %H:%M:%S")))
endTimeStamp = int(time.mktime(time.strptime(end, "%Y-%m-%d %H:%M:%S")))
standardStartTimeStamp = int(time.mktime(time.strptime(standard_start, "%Y-%m-%d %H:%M:%S")))
standardEndTimeStamp = int(time.mktime(time.strptime(standard_end, "%Y-%m-%d %H:%M:%S")))
# 定义一下 开始时间的差值和结束时间的差值,为了避免后面两个 if 语句匹配不上时,不能使用这两个变量
startDifferentTime = 0
endDifferentTime = 0
# 规定时间范围 也就是指 正常规定的工作时间
if(standardStartTimeStamp < startTimeStamp < standardEndTimeStamp):
# 说明开始时间在规定时间范围之外
startDifferentTime = standardEndTimeStamp - startTimeStamp
if(standardStartTimeStamp < endTimeStamp < standardEndTimeStamp):
# 说明结束时间在规定时间范围之外
endDifferentTime = endTimeStamp - standardStartTimeStamp
# 算出真正的工作时间 单位为 s
timeDifferent =(endTimeStamp - startTimeStamp) - (startDifferentTime + endDifferentTime) if (startDifferentTime + endDifferentTime) > 0 else (endTimeStamp - startTimeStamp) - 1.5 * 3600
# 判断一下 若真正工作时间 小于 0,则为 0,不小于 0,则为本身
timeDifferent = timeDifferent if timeDifferent>0 else 0
print(timeDifferent)
# 转换工作时间的单位
timeDifferentHour = (timeDifferent / (60*60))
print(timeDifferentHour)
# 多个时间段过滤
timeFilterList = [["2020-01-03 12:00:00","2020-01-03 13:30:00"],["2020-01-03 14:00:00","2020-01-03 16:30:00"]]
standardTimeStamp = 0
startTimeStamp = int(time.mktime(time.strptime(start, "%Y-%m-%d %H:%M:%S")))
endTimeStamp = int(time.mktime(time.strptime(end, "%Y-%m-%d %H:%M:%S")))
for i in timeFilterList:
startDifferentTime = 0
endDifferentTime = 0
standardStartTimeStamp = int(time.mktime(time.strptime(i[0], "%Y-%m-%d %H:%M:%S")))
standardEndTimeStamp = int(time.mktime(time.strptime(i[1], "%Y-%m-%d %H:%M:%S")))
if (standardStartTimeStamp < startTimeStamp < standardEndTimeStamp):
# 说明开始时间在规定时间范围之外
startDifferentTime = standardEndTimeStamp - startTimeStamp
if (standardStartTimeStamp < endTimeStamp < standardEndTimeStamp):
# 说明结束时间在规定时间范围之外
endDifferentTime = endTimeStamp - standardStartTimeStamp
standardTimeStamp = standardTimeStamp + (endDifferentTime + startDifferentTime) if (endDifferentTime + startDifferentTime) > 0 else standardTimeStamp + (standardEndTimeStamp - standardStartTimeStamp)
timeDifferent = endTimeStamp - startTimeStamp - standardTimeStamp
timeDifferent = timeDifferent if timeDifferent > 0 else 0
timeDifferentHour = (timeDifferent / (60*60))
print(timeDifferentHour)
12-04
2402
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-14