Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing DateTime Comparisons in Filter SQLAlchemy

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.

like image 570
user1431282 Avatar asked Jul 25 '13 21:07

user1431282


2 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.

like image 174
Ian Wilson Avatar answered Nov 18 '22 09:11

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! :)

like image 3
cujo Avatar answered Nov 18 '22 09:11

cujo