使用SqlAlchemy + python在datetime字段上按时过滤

时间:2014-07-08 10:08:47

标签: mysql sqlalchemy

我有一个LocationEvent模型,其timestamp属性是DateTime字段。我想编写一个函数,它将采用start_timeend_time(它们是python time个对象)并将返回两次之间的LocationEvent个对象 - 无论如何约会。

我尝试在SQLAlchemy中使用extract函数,但无法成功。我尝试了以下内容 -

LocationEvent.query.filter(sqlalchemy.extract('time', LocationEvent.timestamp) >= start_time)

这给了我以下错误 -

sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1064, "You have an error in your SQL 
syntax; check the manual that corresponds to your MySQL server version for the right syntax to 
use near 'time FROM location_event.timestamp) >= '08:00:00'' at line 3") 'SELECT 
location_event.id AS location_event_id, location_event.latitude AS location_event_latitude, 
location_event.longitude AS location_event_longitude, location_event.type AS 
location_event_type, location_event.timestamp AS location_event_timestamp, 
location_event.creation_date AS location_event_creation_date \nFROM location_event \nWHERE 
EXTRACT(time FROM location_event.timestamp) >= %s' ('08:00:00',)

关于如何实现这一点的任何想法?

1 个答案:

答案 0 :(得分:2)

我能够使用以下内容完成此操作 -

from sqlalchemy import Time, cast
LocationEvent.query.filter(cast(LocationEvent.timestamp, Time) >= start_time, cast(LocationEvent.timestamp, Time) <= end_time).all()