我怎样才能比较SQLAlchemy中日期时间的日期?

时间:2014-04-13 11:01:10

标签: python datetime sqlalchemy flask flask-sqlalchemy

我在SQLAlchemy中有一个查询:

weekly_schedule = WeeklyHour.query.filter(
    and_(
        WeeklyHour.start_time.in_(week_dates),
        WeeklyHour.end_time.in_(week_dates),
        WeeklyHour.employee == employee
        )
    ).all()

我这样得到当周的日期:

today = datetime.datetime.today()
week_dates = [today + datetime.timedelta(days=i) for i in xrange(0 - today.weekday(), 7 - today.weekday())]

这将返回datetimes中当前周的列表。像这样:

[datetime.date(2014, 4, 7), datetime.date(2014, 4, 8), datetime.date(2014, 4, 9), datetime.date(2014, 4, 10), datetime.date(2014, 4, 11), datetime.date(2014, 4, 12), datetime.date(2014, 4, 13)]

问题是当员工在那天开始和结束时WeeklyHourdatetimeweek_dates是设置为now()的特定时间。我永远不会得到结果,因为time的{​​{1}}将不匹配。我真正想要比较的是datetime的{​​{1}}部分。我当前的解决方案(有效但是很愚蠢)是存储date的单独datetime

1 个答案:

答案 0 :(得分:3)

不要在一周中的所有日子里“查询”,而是以天为限。

today = date.today()
start_of_week = today - timedelta(days=today.weekday())
start_of_following_week = start_of_week + timedelta(days=7)

weekly_schedule = WeeklyHour.query.filter(
    and_(
        WeeklyHour.start_time >= start_of_week,  # On or after Monday
        WeeklyHour.end_time < start_of_following_week, # Before next Monday
        WeeklyHour.employee == employee
        )
    ).all()