14

如何在 python 中使用 sqlalchemy 重写以下 sql 语句。我一直在寻找 30 分钟,但仍然找不到任何解决方案。

DATEADD(NOW(), INTERVAL 1 DAY)

或者

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

提前致谢

4

5 回答 5

37

为了完整起见,以下是使用 using 生成确切 SQL 的方法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()))

这导致:

>>> 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)'

或者,您可以使用text()对象来指定间隔:

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

tomorrow = func.dateadd(func.now(), text('interval 1 day'))
于 2013-03-22T15:12:10.417 回答
9

SQLAlchemy 日期自动映射到 Python 日期时间对象,所以你应该能够做到:

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)
于 2013-03-22T15:02:14.293 回答
3

Doobeh 在我打字的时候打败了我,这是我要发布的烧瓶 sqlalchemy 示例(以补充简单的 sqlalchemy 示例):

from flask.ext.sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta

db = 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)

您也可以将默认值作为可调用对象传递:

from flask.ext.sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta

db = 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)
于 2013-03-22T15:06:16.750 回答
0
from datetime import datetime, timedelta
from dateutil import tz

new_date = datetime.now(tz=tz.tzlocal()) + timedelta(days=1)
new_item = Expire(expire=new_date)
session.save(new_item)
session.commit()
于 2016-12-29T21:20:35.943 回答
0

您可以使用 MySQL timestampaddinsted dateadd

更多详细信息http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampadd

于 2016-08-26T00:16:10.907 回答