使用SqlAlchemy插入MySQL时间戳列值

时间:2013-07-23 19:41:45

标签: python mysql sqlalchemy timestamp

我有一个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()

2 个答案:

答案 0 :(得分:12)

datetime个对象转换为时间戳,因此您只需使用:

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

datetime.utcnow()如果您想使用utc保存它。默认值(CURRENT_TIMESTAMP)使用本地时区,因此datetime.now()更接近于此 - 但它几乎总是优先以UTC格式存储与时间相关的数据,并且仅在向数据库提供数据时才进行时区转换。用户。

答案 1 :(得分:8)

mata回答非常明确如何添加时间戳值。如果您要在automaticallyinsert上添加update添加的时间戳。您可以考虑使用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):。 在模型init上调用HarvestSources.register()updated_atcreated_at列会自动更新。

相关问题