SQLAlchemy 在 MySQL 中以微秒精度存储日期时间

SQLAchemy store datetime with microsecond precision in MySQL

我正在尝试将日期时间作为时间戳存储在 MySQL 中,精度为微秒:2020-05-10 16:00:00.666666 使用 SQLAchemy

这是我的模型:

class Order(Base):
  __tablename__ = "order"

  order_id = Column("id", String(50), primary_key=True)
  published_at = Column(
      "published_at", TIMESTAMP, nullable=True
  )

这是我的插入语句(在会话中完成):

order = Order(
            order_id=id,
            published_at=published_at,  #python datetime of format: 2020-05-10 15:00:00.555555+00:00
        )
session.add(order)
session.commit()

使用 SQLLite 我得到了我所期望的。但是,当使用 MySQL 时,我会松开小数部分并得到 2020-05-10 15:00:00。有什么解决办法吗?

提前致谢

TIMESTAMP 已像 from sqlalchemy import TIMESTAMP 一样导入,但是这不会让您访问 fsp 参数,因此您必须使用 sql 特定方言:from sqlalchemy.dialects.mysql import TIMESTAMP。然后你可以在模型中使用 TIMESTAMP(fsp=6) 。参考 https://docs.sqlalchemy.org/en/13/dialects/mysql.html#sqlalchemy.dialects.mysql.TIMESTAMP