【问题标题】:Insert MySQL timestamp column value with SqlAlchemy使用 SqlAlchemy 插入 MySQL 时间戳列值
【发布时间】:2013-07-23 19:41:45
【问题描述】:

我有一个 sqlalchemy 类映射到 MySQL innoDB 中的数据库表。该表有几列,除了 TIMESTAMP 列之外,我能够成功填充它们:

映射:

class HarvestSources(Base):
    __table__ = Table('harvested', metadata, autoload=True)

MySQL 上的列是一个 TIMESTAMP,它的默认值是 CURRENT_TIMESTAMP,但是当我插入一行时,它会被 NULL 填充。

如果默认值不起作用,那么我需要手动设置时间戳,我该怎么做。

SqlAlchemy 代码向表中插入行:

source = HarvestSources()
source.url = url
source.raw_data = data
source.date = ?

DB.session.add(source)
DB.session.commit()

【问题讨论】:

    标签: python mysql sqlalchemy timestamp


    【解决方案1】:

    datetime 对象被转换为时间戳,所以你可以使用:

    from datetime import datetime
    ...
    source.date = datetime.now()
    

    datetime.utcnow() 如果您想使用 utc 保存它。默认 (CURRENT_TIMESTAMP) 使用本地时区,因此 datetime.now() 更接近于本地时区 - 但几乎总是最好将时间相关数据存储在 UTC 中,并且仅在向用户呈现数据时进行时区转换。

    【讨论】:

      【解决方案2】:

      mata 的答案非常清楚如何添加时间戳值。如果您想在insertupdate 上添加添加automatically 的时间戳。您可以考虑有一个 BaseMixin 类并为每个类注册 sqlalchemy 事件。示例实现如下:

      class BaseMixin(object):
      
        __table_args__ = {'mysql_engine': 'InnoDB'}
      
        id = sa.Column(sa.Integer, primary_key=True)
        created_at = sa.Column('created_at', sa.DateTime, nullable=False)
        updated_at = sa.Column('updated_at', sa.DateTime, nullable=False)
      
        @staticmethod
        def create_time(mapper, connection, instance):
           now = datetime.datetime.utcnow()
           instance.created_at = now
           instance.updated_at = now
      
        @staticmethod
        def update_time(mapper, connection, instance):
           now = datetime.datetime.utcnow()
           instance.updated_at = now
      
        @classmethod
        def register(cls):
           sa.event.listen(cls, 'before_insert', cls.create_time)
           sa.event.listen(cls, 'before_update', cls.update_time)
      

      将您的 class HarvestSources(Base): 更改为 class HarvestSources(Base, BaseMixin):。 在你的模型初始化上调用HarvestSources.register()updated_atcreated_at 列将自动更新。

      【讨论】:

        猜你喜欢
        • 2015-06-21
        • 1970-01-01
        • 1970-01-01
        • 2017-05-31
        • 1970-01-01
        • 2014-07-21
        • 1970-01-01
        • 2012-09-11
        • 1970-01-01
        相关资源
        最近更新 更多