Make Sqlalchemy Use Date In Filter Using Postgresql

后端 未结 4 1933
广开言路
广开言路 2021-02-05 05:32

I\'m trying to perform the following query in Sqlalchemy.

Select * from \"Mytable\" where Date(date_time_field) = \"2011-08-16\";

I have tried

4条回答
  •  半阙折子戏
    2021-02-05 05:57

    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 import select, func
     print select([func.date('2004-10-19 10:23:54')])
    

    will produce following SQL:

     SELECT date(: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
    
    class convert_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 import select, func
    print select([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
    

提交回复
热议问题