4
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 日期时间操作来解决这个问题?

4

3 回答 3

9
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
于 2013-07-19T02:25:03.230 回答
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])
于 2013-07-19T02:12:29.397 回答
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

这就是我得到的所有解决方案。对此有何增强?

于 2013-07-19T02:25:04.963 回答