python 处理重叠时间问题

同一天中的一连串不连续时间段,合并其中重叠时间,如:

StartTime     EndTime
06:10:58     08:15:28
07:38:56     10:34:45
10:55:00     11:34:00
13:09:34     17:45:23
14:23:12     15:24:14
16:14:25     17:52:15
合并后为:
StartTime     EndTime
06:10:58     10:34:45
10:55:00     11:34:00
13:09:34     17:52:15
# -*- coding: UTF-8 -*-
import datetime

def A():
    # 创建数据
    a1 = "2011,03,01,10,55,00"
    b1 = "2011,03,01,11,34,00"
    a2 = "2011,03,01,13,09,34"
    b2 = "2011,03,01,17,45,23"
    a3 = "2011,03,01,14,23,12"
    b3 = "2011,03,01,15,24,14"
    a4 = "2011,03,01,07,38,56"
    b4 = "2011,03,01,10,34,45"
    a5 = "2011,03,01,06,10,58"
    b5 = "2011,03,01,08,15,28"
    a6 = "2011,03,01,16,14,25"
    b6 = "2011,03,01,17,52,15"


    a = [a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6]

    for n,i in enumerate(a):
        a[n] = datetime.datetime.strptime(i,"%Y,%m,%d,%H,%M,%S")

    b=[]
    for i in range(len(a)//2):
        b.append([a[2*i],a[2*i+1]])

    return b

def B(b:list):
    # 处理数据,合并重复时间
    b.sort(key=lambda x:x[0])
    for n in range(len(b)-1):
        m=n+1
        if b[n][1] > b[m][0]:
            if b[n][1] > b[m][1]:
                b[m] = b[n]

            else:
                b[m][0] = b[n][0]

            b[n]=None

    c = []
    for i in b:
        if i:
            c.append(i)

    return c

def C(c):
    # 时间段求和,计算总时间
    d = datetime.timedelta()
    for i in c:
        print(i[1]-i[0])
        d+=i[1]-i[0]

    print(d,type(d))
    return d.days*24 + d.seconds/3600


if __name__ == "__main__":
	# 创建数据,返回[[时间段],[时间段],[时间段],....]
    b = A()
    print(b)
    # 处理数据,合并重复时间段,返回[[时间段],[时间段],[时间段],....]
    c = B(b)
    print(c)
    # 计算所用时间 float(小时为单位)
    d = C(c)
    print(d)

你可能感兴趣的:(datetime,重叠,时间,python)