我想看看用户预订的日期是否在数据库中的两个其他日期时间对象之间。
我的表start_time和end_time有两个不同的时间,所以start_time表示预订开始时,end_time表示结束时间,这里是代码:
def parse_time(time):
tdateime = str(time)
date = parse(tdateime)
return date
start = '2017-08-23 11:00:00'
end = '2017-08-23 11:50:00'
p1 = parse_time(start)
p2 = parse_time(end)
p3 = 'the date to be checked'
check_is_free = Appointment.query.filter(Appointment.start_time == p1).filter(Appointment.end_time == p2).first()
original_start_date = check_is_free.start_time
original_end_date = check_is_free.end_time
if check_is_free:
if original_start_date <= p3 <= check_is_free.end_time:
error = 'already reserved.'
return jsonify({'occupied':error})
这里的结尾是服务时间段,例如,约会从11:00开始,服务是50分钟,timedelta
将这50分钟添加到开始时间,所以最终结果将是这是一段时间,这段时间必须很忙,你不能在这段时间内写一本书。
如果用户想要预订服务,例如今天在'11:30:00'它应该给他一个已经保留的错误消息,但我怎样才能获得第三个日期??,事实上,我正在使用bootstrap-datepicker
选择日期时间,我只有一个字段来选择开始日期和时间。
我尝试通过解析开始时间并将其值放在变量 p3 中进行一些更改,但是在这里它将忽略上面的所有代码并且将接受约会,因为< strong> p3 与开始相同,如果开始时间在 check_is_free 中匹配,则会向我提供已预订的服务,此处错误会提高,但如果我将开始时间改为仅一分钟, check_is_free 将返回无,这意味着我将不会接受约会。
答案 0 :(得分:1)
您是否可以过滤以查找是否有任何Appointment
与用户所需的约会窗口重叠?我的意思是:
# User's desired appointment window is start_time to end_time
# an appointment is not overlapping, if
# - the end_time is before an existing start time, or
# - the start_time is after an existing end time
overlapping = session.query(Appointment).filter(
not_(
or_(Appointment.start_time > end_time,
Appointment.end_time < start_time)))
这是一个完整的工作示例,您可以尝试:
from datetime import datetime, timedelta
from sqlalchemy import create_engine, Column, DateTime, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import or_, not_
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Appointment(Base):
__tablename__ = 'appointments'
id = Column(Integer, primary_key=True)
start_time = Column(DateTime, nullable=False)
end_time = Column(DateTime, nullable=False)
Base.metadata.create_all(engine)
session = Session()
existing_appointment = Appointment(id=1,
start_time=datetime(2017,8,23,11,0),
end_time=datetime(2017,8,23,11,50))
session.add(existing_appointment)
session.commit()
def check_appointment(start_time):
end_time = start_time + timedelta(minutes=20)
overlapping = session.query(Appointment).filter(
not_(
or_(Appointment.start_time > end_time,
Appointment.end_time < start_time)))
return not overlapping.count()
print('check 2017-08-23 11:30 (should be False): {}'.format(check_appointment(datetime(2017,8,23,11,30))))
print('check 2017-08-23 10:30 (should be True): {}'.format(check_appointment(datetime(2017,8,23,10,30))))