我将持续时间表示为一对像这样的日期时间对象
(datetime(2014, 1, 23, 14, 49, 6, 185955), datetime(2015, 4, 18, 14, 49, 6, 185955))
我有一个像这样的元组列表
[(datetime(2014, 1, 23, 14, 49, 6, 185955), datetime(2015, 4, 18, 14, 49, 6, 185955)), (datetime(2015, 2, 2, 14, 49, 6, 185955), datetime(2015, 10, 23, 14, 49, 6, 185955)),]
现在如何计算列表中所有持续时间(此处为datetime对象对)的(小时,分钟,秒)重叠持续时间?
E.g:
A C B D G E H I J F
|-----------------------|
|--------------------------|
|-----------------------|
|--------------| |-----|
这里AB,CD是一对日期时间对象。如何在(小时,分钟,秒)中获得重叠CB 这样的一对列表?
答案 0 :(得分:1)
试试这个:
from datetime import datetime
t = [(datetime(2014, 1, 23, 14, 49, 6, 185955), datetime(2015, 4, 18, 14, 49, 6, 185955)), (datetime(2015, 2, 2, 14, 49, 6, 185955), datetime(2015, 10, 23, 14, 49, 6, 185955))]
def time_overlap(t):
overlap = (min(t[0][1], t[1][1]) - max(t[0][0], t[1][0]))
days = overlap.days+1
hours, remainder = divmod(overlap.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
hours += days*24
return (hours,minutes,seconds)
print(time_overlap(t))
输出:
(1824, 0, 0)
要查找多个日期时间的重叠,请执行以下操作:
from datetime import datetime
t = [(datetime(2014, 1, 23, 14, 49, 6, 185955), datetime(2015, 4, 18, 14, 49, 6, 185955)), (datetime(2015, 2, 2, 14, 49, 6, 185955), datetime(2015, 10, 23, 14, 49, 6, 185955))]
def time_overlap(t):
overlap = (min([x[1] for x in t]) - max([x[0] for x in t]))
days = overlap.days+1
hours, remainder = divmod(overlap.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
hours += days*24
return (hours,minutes,seconds)
print(time_overlap(t))