Siddharth
Siddharth

Reputation: 5219

Filtering on time on a datetime field using SqlAlchemy + python

I have a LocationEvent model which has a timestamp property which is a DateTime field. I want to write a function which will take a start_time and end_time (which are python time objects) and will return the LocationEvent objects which are between those two times - irrespective of the date.

I tried using the extract function in SQLAlchemy but was not able to succeed. I tried the following -

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

This gives me the following error -

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',)

Any idea on how can I achieve this?

Upvotes: 1

Views: 1463

Answers (1)

Siddharth
Siddharth

Reputation: 5219

I was able to do this using the following -

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

Upvotes: 3

Related Questions