本地SQL函數可以使用使用func
模塊
from sqlalchemy import func
from datetime import date
my_data = session.query(MyObject).filter(
func.date(MyObject.date_time) == date.today()
).all()
調用func.date
from sqlalchemy import select, func
print select([func.date('2004-10-19 10:23:54')])
會產生被調用以下SQL:
SELECT date(:date_2) AS date_1
您也可以聲明自己的快捷方式到SQL函數:
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
使用,如:
from sqlalchemy import select, func
print select([func.convert_tz(func.now(), '+00:00', '-05:00')])
它會生成以下SQL:
SELECT convert_tz(now(), :param_1, :param_2) AS convert_tz_1
完美!謝謝! – user1914881