Doing DateTime Comparisons in Filter SQLAlchemy

Question:

I’m a bit confused about filtering in SQLAlchemy.

I currently am trying to filter out entries greater than 10 weeks, so I have

current_time = datetime.datetime.utcnow()

potential = session.query(Subject).filter(Subject.time < current_time - datetime.timedelta(weeks=10))

However, the potential.count() always returns 0.

My theory is that I am not using the filter statement correctly because when I try to use a column that is not of type Column(DateTime()) but instead

Column(String(250))

like

 potential = session.query(Subject).filter(Subject.string_field < current_time - datetime.timedelta(weeks=10))

SQLAlchemy will still not complain.

Also, when I do a manual check with

curr_time - session.query(Subject).first().time > datetime.timedelta(weeks=10)

I get True which implies that the count should not be 0.

Am I missing something obvious? Any help would be appreciated.

Asked By: user1431282

||

Answers:

If you switch the < to a > you can get all subjects within the last ten weeks:

current_time = datetime.datetime.utcnow()

ten_weeks_ago = current_time - datetime.timedelta(weeks=10)

subjects_within_the_last_ten_weeks = session.query(Subject).filter(
    Subject.time > ten_weeks_ago).all()

Filter generates a WHERE clause which includes results matching the clause. So the results are not “filtered out” but are included.

Answered By: Ian Wilson

OR if you use SQLAlchemy "and_" you can find all records between the dates:

from sqlalchemy import and_
#I use the .now(tz=...) because it is preferred over .utcnow()
#There is a waring on 
#https://docs.python.org/3/library/datetime.html#examples-of-usage- 
#datetime
current_time = datetime.datetime.now(tz=timezone.utc)
ten_weeks_ago = current_time - datetime.timedelta(weeks=10)
subjects_BETWEEN_NOW_AND_last_ten_weeks = session.query(Subject).filter(
    and_(Subject.time > ten_weeks_ago,
    Subject.time < ten_weeks_ago)).all()

just another way of doing it! 🙂

Answered By: cujo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.