Thor
Thor

Reputation: 650

SQLAlchemy query returning results with values outside filter criteria

I'm using SQLAlchemy to access an SQLite db. I have populated the database with 50,000 entries as defined by the Event ORM below. When I query the database and filter for 'time' greater than some value, I consistently get results with time values before the requested time.
How do I craft the query such that if properly filters based on time?

Here is my query code:

query = session.query(Event)
query = query.filter(Event.time > starttime)

Here is the Event ORM

Base = declarative_base()

class Event (Base):
  __tablename__ = 'events'
  eventid = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
  time = sqlalchemy.Column(sqlalchemy.Integer)
  value = sqlalchemy.Column(sqlalchemy.Float)
#end class

Upvotes: 0

Views: 390

Answers (1)

jackotonye
jackotonye

Reputation: 3853

Your model Event.time. is an Integer Column if you want to filter by a date time object you have to change the column of use datetime object to filter.

from sqlalchemy import func
from dateutil import tz

time = Column(DateTime(timezone=True), nullable=False,
                              server_default=func.now())
starttime = datetime.datetime.now(tz=tz.tzlocal()) # local timezone

query = session.query(Event).filter(Event.time > starttime)

Upvotes: 1

Related Questions