Time Interval overlap in python

2019-02-28 00:37发布

问题:

Suppose I have list of time interval like

a = [datetime.time(0,0),datetime.time(8,0)]

Now I Have lacs of intervals in list like given below.

b = [[datetime.time(0,0),datetime.time(8,0)], [datetime.time(0,0),datetime.time(10,0)], [datetime.time(0,0),datetime.time(23,59,59)], [datetime.time(15,0),datetime.time(9,0)], [datetime.time(9,0),datetime.time(15,0)]]

We have to filter list b with intervals containing interval a. like in example result will be.

b = [[datetime.time(0,0),datetime.time(8,0)], [datetime.time(0,0),datetime.time(10,0)], [datetime.time(0,0),datetime.time(23,59,59)], [datetime.time(15,0),datetime.time(9,0)]]

Note: I have changed end time from 00 to 23:59:59 but the case remain persistent as we need to understand that daily interval of 00:00 to 08:00 is contained in interval of 15:00 to 09:00

Hint: I have divided 15:00 to 09:00 into two intervals: 00:00-09:00 and 15:00-23:59:59

回答1:

Your code has errors (usage of datetime/datetime.time).

This code will filter out from b everything, that does not overlap with a:

b = [x for x in b if a[0] < x[1] and x[0] < a[1]]