简体   繁体   中英

SqlAlchemy: Convert datetime column to date column

I'm trying to convert the datetime column to date

def filter_between_dates(query, req, db_col):

    date_from = req.get_param('date_from')
    #date_to = req.get_param('date_to')

    query = query.filter(cast(db_col,DATE) == date_from)

    return query

The error showed: "name 'DATE' is not defined" I tried adding import DATE , and got "ImportError:cannot import name 'DATE'"

Maybe I'm doing this wrong from the beginning. Please guide.

You have to import it.

from sqlalchemy import Date, cast
...
def filter_between_dates(query, req, db_col):

    date_from = req.get_param('date_from')
    #date_to = req.get_param('date_to')

    query = query.filter(cast(db_col,Date) == date_from)

    return query

Or you can do it with func:

from sqlalchemy import func
...
query = query.filter(func.date(db_col) == date_from)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM