Python:在时间范围内获得分钟重叠

时间:2013-07-19 02:07:26

标签: python python-datetime

date_base_start = datetime(2013, 07, 17, 20, 0) #July 17,2013 08:00PM
date_base_end = datetime(2013, 07, 17, 22, 0)   #July 17,2013 10:00PM

date_1_start = datetime(2013, 07, 17, 21, 0)    #July 17,2013 09:00PM
date_1_end = datetime(2013, 07, 17, 21, 30)     #July 17,2013 09:30PM

date_2_start = datetime(2013, 07, 17, 19, 0)    #July 17,2013 07:00PM
date_2_end = datetime(2013, 07, 17, 23, 0)      #July 17,2013 11:00PM

date_3_start = datetime(2013, 07, 17, 19, 0)    #July 17,2013 07:00PM
date_3_end = datetime(2013, 07, 17, 22, 0)      #July 17,2013 10:00PM

#Expected Result date_base_start, date_base_end VS the ff:
#     date_1_start, date_1_end : 30min
#     date_2_start, date_2_end : 120min
#     date_3_start, date_3_end : 120min

解决这个问题需要什么python日期时间操作?

3 个答案:

答案 0 :(得分:8)

delta = min(date_1_end,date_base_end)-max(date_1_start,date_base_start)
#
# Check if delta is negative, 
#
if delta.seconds < 0:
         print 0
else:
         print delta.seconds/60.0

答案 1 :(得分:2)

def overlap(range1,range2):
    start_datetime = max(range1[0],range2[0])
    end_datetime   = min(range1[1],range2[1])
    return end_datetime-start_datetime

print overlap([date_base_start,date_base_end],[date_3_start, date_3_end])

答案 2 :(得分:2)

def minutes_overlap_test(date_base_start, date_base_end, date_comp_start, date_comp_end):
    tmp_start = date_base_start
    tmp_end = date_base_end

    if date_comp_start > tmp_start:
        tmp_start = date_comp_start
    if date_comp_end < tmp_end:
        tmp_end = date_comp_end

    d1_ts = time.mktime(tmp_start.timetuple())
    d2_ts = time.mktime(tmp_end.timetuple())
    return int(d2_ts-d1_ts) / 60

这是我得到的所有解决方案。对此有任何改进吗?