How to get all objects with a date that fall in a specific month SQLAlchemy

Viewed 10655

I have a simple SQLAlchemy model:

class Event(Base):
    """ The SQLAlchemy declarative model class for a Event object. """
    __tablename__ = 'events'
    id = Column(Integer, primary_key=True)
    date = Column(DateTime)
    title = Column(Text)

How do I filter a SQLAlchemy query so that only events in a specific month are returned?

3 Answers

I was wondering the same thing that Brady Huang was wondering. So to expand on @scottydelta's excellent answer: You can just stack the filters on top of each other. So if you want to extract every Event from July 2018 you should use

from sqlalchemy import extract  

session.query(Event).filter(extract('year', Event.date)==2018).filter(extract('month', Event.date)==7).all()
Related