Question

Using plain Oracle SQL, I would use:

select *
from mytable
where 
to_date(date_d, 'dd-mon-yyyy') == to_date('01-Jan-2013', 'dd-mon-yyyy')

Now using SQLAlchemy, I'm at a loss.

from datetime import datetime

dt = myTable.c.date_d == datetime(2013, 1, 1)
q = session.query(myTable).filter(dt)
q.first()

Will give me incorrect results, because date_d is varchar, so it won't translate to date unless I run an Oracle function to convert the datatype within the query. How can I do that?

Was it helpful?

Solution

Turns out I didn't need to convert the datatype. SQLAlchemy seems to do that transparently. However, If I feel like doing it explicitly:

from sqlalchemy import func

dt = func.to_date(myTable.c.date_d, 'dd-mon-yyyy') == datetime(2013, 1, 1)
q = session.query(dt)
q.first()

My incorrect results were due to an unrelated mistake.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top