我有开始和结束时间。如下所示
def overlap(start1, end1, start2, end2):
pass
因此,两个时间安排都会安排会议,我想确保没有会议相互重叠。
因此,如果两次会议重叠,则会返回True
其他False
。
我是用JavaScript完成的,我想用Python做,因为我是Python的新手,我不知道应该使用什么模块以及如何使用它们。 这是我在JavaScript上的实现。
// time of first timespan
var x = new Date('01/01/2001 8:30:00').getTime();
var y = new Date('01/01/2001 9:30:00').getTime();
// time of second timespan
var a = new Date('01/01/2001 8:54:00').getTime();
var b = new Date('01/01/2001 9:00:00').getTime();
if (Math.min(x, y) <= Math.max(a, b) && Math.max(x, y) >= Math.min(a, b)) {
// between
}
答案 0 :(得分:1)
这个怎么样:
from dateutil import parser
def date_overlap(date1, date2):
obj_1 = map(parser.parse, date1)
obj_2 = map(parser.parse, date2)
# is latest start before earliest end? If so, overlap!
if max(obj_1[0], obj_2[0]) < min(obj_1[1], obj_2[1]):
return True
else:
return False
date_1 = ('01/01/2001 8:30:00', '01/01/2001 9:30:00')
date_2 = ('01/01/2001 8:54:00', '01/01/2001 9:00:00')
print date_overlap(date_1, date_2)
dateutil.parser
将字符串转换为日期。如果我们最新的开始是在我们最早的结束之前,那就有重叠。
注意:如果您使用的是Python 3.x,则需要将两个map
输出包装为如下所示的列表:
from dateutil import parser
def date_overlap(date1, date2):
obj_1 = list(map(parser.parse, date1))
obj_2 = list(map(parser.parse, date2))
# is latest start before earliest end? If so, overlap!
if max(obj_1[0], obj_2[0]) < min(obj_1[1], obj_2[1]):
return True
else:
return False
date_1 = ('01/01/2001 8:30:00', '01/01/2001 9:30:00')
date_2 = ('01/01/2001 8:54:00', '01/01/2001 9:00:00')
print date_overlap(date_1, date_2)
答案 1 :(得分:0)
import datetime
def overlap(start1, end1, start2, end2):
if start1 < start2 and end1 > start2 or \
start1 > start2 and end1 < end2 or \
start1 > start2 and start1 < end2:
return True
else:
return False
start_date1 = datetime.datetime(2017,1,1)
end_date1 = datetime.datetime(2017,1,3)
start_date2 = datetime.datetime(2017,1,2)
end_date2 = datetime.datetime(2017,1,4)
print(overlap(start_date1, end_date1, start_date2, end_date2))
你也可以使用时间。
答案 2 :(得分:0)
这是我在短时间内可以做的JS代码的最接近的解释:
from datetime import datetime
#assuming time format comes in a string like this: '8:30:00'
#assumming provided time has sense, i.e. end1 > start1 and end2 > start2
TIME_FORMAT = '%H:%M:%S'
def overlap(start1, end1, start2, end2):
#transform time
start1_time = datetime.strptime(start1, TIME_FORMAT )
end1_time = datetime.strptime(end1, TIME_FORMAT )
start2_time = datetime.strptime(start2, TIME_FORMAT )
end2_time = datetime.strptime(end2, TIME_FORMAT )
#checking conditions
if (min(start1_time, end1_time) <= max(start2_time, end2_time)) \
and \
(max(start1_time, end1_time) >= min(start2_time, end2_time)):
return True
else:
return False
>>>overlap('8:30:00','9:30:00','8:54:00','9:00:00')
True
>>>overlap('8:30:00','9:30:00','9:54:00','10:00:00')
False
PS:唯一的模块是datetime
,因为Python在其核心提供了min
和max
。
EDIT1:仅使用时间而非日期。
EDIT1:缩进更新。
答案 3 :(得分:0)
def overlap(start1, end1, start2, end2):
return (start1 <= start2 <= end1) or (start2 <= start1 <= end2)