Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get query a certain period of datetime in Flask sqlalchemy?

In Flask, I have a model named User, like this:

class Post(db.Model):
    __tablename__ = 'post'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    content = db.Column(db.Text)
    post_time = db.Column(db.DateTime(), index=True, default=datetime.now)

I wanna query a certain period datetime, for example, I need to query all the posts posted between 2016-11-01 and 2016-11-30
I tried to achieve this by Stitching string, like this:

posts = Post.query.filter(Post.post_time <= year_month+'-30').filter(Post.post_time >= year_month+'-01')

but this is awkward, is there any better way to to that?

like image 626
TreeCatCat Avatar asked Nov 06 '16 09:11

TreeCatCat


1 Answers

Use the datetime.date module:

from datetime import date

start = date(year=2016,month=11,day=1)
end = date(year=2016,month=11,day=30)

posts = Post.query.filter(Post.post_time <= end).filter(Post.post_time >= start)

datetime documentation

like image 94
Matt Healy Avatar answered Oct 16 '22 18:10

Matt Healy