Skip to content Skip to sidebar Skip to footer

Make Sqlalchemy Use Date In Filter Using Postgresql

I'm trying to perform the following query in Sqlalchemy. Select * from 'Mytable' where Date(date_time_field) = '2011-08-16'; I have tried several methods. Some here on SO. But non

Solution 1:

Using @Ants Aasma Comment.

And to Keep it clean for any web search.

from sqlalchemy import Date, cast
from datetime import date

my_data = session.query(MyObject).\
filter(cast(MyObject.date_time,Date) == date.today()).all()

Thank you all who tried to solve this problem :)

Solution 2:

Native SQL functions can be invoked using using func module

from sqlalchemy import func
from datetime import date

my_data = session.query(MyObject).filter(
    func.date(MyObject.date_time) == date.today()
).all()

Calling func.date

 from sqlalchemy importselect, funcprintselect([func.date('2004-10-19 10:23:54')])

will produce following SQL:

SELECTdate(:date_2) AS date_1

You can also declare your own shortcuts to SQL functions:

from sqlalchemy.sql.functions import GenericFunction
from sqlalchemy.types import DateTime

classconvert_tz(GenericFunction):
    """
    Sqlalchemy shortcut to SQL convert timezone function

    :param DateTime datetime
    :param str from_tz: The timezone the datetime will be converted from
    :param str to_tz: The timezone the datetime will be converted from
    :returns: Datetime in another timezone
    :rtype: DateTime or None if timezones are invalid

    """type = DateTime

Used like:

from sqlalchemy importselect, funcprintselect([func.convert_tz(func.now(), '+00:00', '-05:00')])

It will generate following SQL:

SELECT convert_tz(now(), :param_1, :param_2) AS convert_tz_1

Solution 3:

in postgreSQL if date_time_field is one field of your table then quer must like this. Select * from Mytable where date_time_field = '2011-08-16'

Solution 4:

Here are generic solution that also works in SQLite:

day = date.today()
next_day = day + timedelta(days=1)
my_data = session.query(MyObject).filter(MyObject.date_time >= day,  MyObject.date_time < next_day).all()

Post a Comment for "Make Sqlalchemy Use Date In Filter Using Postgresql"