Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DATEADD in sqlalchemy

How can I rewrite the following sql statement with sqlalchemy in python. I have been searching for 30 mins but still couldn't find any solutions.

DATEADD(NOW(), INTERVAL 1 DAY)

or

INSERT INTO dates (expire)
VALUES(DATEADD(NOW(), INTERVAL 1 DAY))

Thanks in advance

like image 375
Alper Avatar asked Mar 22 '13 14:03

Alper


2 Answers

SQLAlchemy dates automagically map to Python datetime objects, so you should just be able to do:

from sqlalchemy import Table, Column, MetaData, DateTime
from datetime import datetime, timedelta

metadata = MetaData()
example = Table('users', metadata,
   Column('expire', DateTime)
)

tomorrow = datetime.now() + timedelta(days=1)

ins = example.insert().values(expire=tomorrow)
like image 195
Doobeh Avatar answered Sep 19 '22 05:09

Doobeh


For completeness sake, here is how you'd generate that exact SQL with using sqlalchemy.sql.func:

from sqlalchemy.sql import func
from sqlalchemy.sql.expression import bindparam
from sqlalchemy import Interval

tomorrow = func.dateadd(func.now(), bindparam('tomorrow', timedelta(days=1), Interval()))

which results in:

>>> from sqlalchemy.sql import func
>>> func.dateadd(func.now(), bindparam('tomorrow', timedelta(days=1), Interval(native=True)))
<sqlalchemy.sql.expression.Function at 0x100f559d0; dateadd>
>>> str(func.dateadd(func.now(), bindparam('tomorrow', timedelta(days=1), Interval(native=True))))
'dateadd(now(), :tomorrow)'

Alternatively you could use a text() object to specify the interval instead:

from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text

tomorrow = func.dateadd(func.now(), text('interval 1 day'))
like image 28
Martijn Pieters Avatar answered Sep 17 '22 05:09

Martijn Pieters