Comparing Dates in Flask-SQLAlchemy


I’ve been trying to compare dates in a query given to SQLALchemy as follows:

start = time.strptime(start, "%d%m%y")
end = time.strptime(end, "%d%m%y")
list_ideas = Idea.query.filter(time >= start, time <= end).all()

However, this does not return results regardless of dates given (where Idea.time = db.Column(db.DateTime, I’ve searched through some other answers regarding this topic and from what I have gathered, I am not making the same mistakes.

In addition, changing the query to Idea.query.filter(time >= start, time <= end, deleted=False).all() gives the error:

TypeError: filter() got an unexpected keyword argument ‘deleted’

Any pointers would be appreciated.

EDIT: I noticed that I was using import time, which may have caused the error. However, after changing it to from time import strptime, I now experience the error:

NameError: global name ‘time’ is not defined


try using the datetime module

from datetime import datetime

Idea.query.filter(Idea.time >= datetime.strptime(start, '%Y-%m-%d'),
                  Idea.time <= datetime.strptime(end, '%Y-%m-%d')).all()

you will just need to change the pattern to match what ever format you are using

Answered By – Michael Moura

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published