Using DATEADD in sqlalchemy Using DATEADD in sqlalchemy flask flask

Using DATEADD in sqlalchemy


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

from sqlalchemy.sql import funcfrom sqlalchemy.sql.expression import bindparamfrom sqlalchemy import Intervaltomorrow = 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 funcfrom sqlalchemy.sql.expression import texttomorrow = func.dateadd(func.now(), text('interval 1 day'))


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

from sqlalchemy import Table, Column, MetaData, DateTimefrom datetime import datetime, timedeltametadata = MetaData()example = Table('users', metadata,   Column('expire', DateTime))tomorrow = datetime.now() + timedelta(days=1)ins = example.insert().values(expire=tomorrow)


Doobeh beat me to it while I was typing, here's a flask-sqlalchemy example I was going to post though (to compliment the plain sqlalchemy example):

from flask.ext.sqlalchemy import SQLAlchemyfrom datetime import datetime, timedeltadb = SQLAlchemy()class Thing(db.Model):    id = db.Column(db.Integer, primary_key=True)    created = db.Column(db.DateTime)c = Thing(created = datetime.utcnow() + timedelta(days=1))print repr(c.created)# datetime.datetime(2013, 3, 23, 15, 5, 48, 136583)

You can pass default as a callable too:

from flask.ext.sqlalchemy import SQLAlchemyfrom datetime import datetime, timedeltadb = SQLAlchemy()def tomorrow():    return datetime.utcnow() + timedelta(days=1)class Thing(db.Model):    id = db.Column(db.Integer, primary_key=True)    publish_date = db.Column(db.DateTime, default=tomorrow)