Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 459
Peter Smit Avatar asked Jul 23 '12 16:07

Peter Smit


2 Answers

A very old question but a better answer is here:

from sqlalchemy import extract  

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

This returns all the records into a database events in July.

like image 170
scottydelta Avatar answered Nov 14 '22 21:11

scottydelta


This should find all the events in June, 2012.

import datetime
import calendar

year = 2012
month = 6

num_days = calendar.monthrange(year, month)[1]
start_date = datetime.date(year, month, 1)
end_date = datetime.date(year, month, num_days)

results = session.query(Event).filter(
    and_(Event.date >= start_date, Event.date <= end_date)).all()
like image 22
Tony Gibbs Avatar answered Nov 14 '22 21:11

Tony Gibbs