You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免SQLAlchemy中datetime类型的精度丢失?

解决SQLAlchemy查询datetime字段丢失毫秒精度的问题

1. 匹配ORM字段与数据库精度

数据库中是精度23(对应毫秒级3位小数)的datetime字段,在SQLAlchemy模型里必须明确指定精度,避免默认配置丢失信息:

from sqlalchemy import Column, DateTime
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class YourModel(Base):
    __tablename__ = 'your_table'
    id = Column(Integer, primary_key=True)
    # 指定precision=3对应数据库的毫秒精度
    created_at = Column(DateTime(precision=3))

如果是MySQL数据库,也可使用方言专属类型更精准匹配:

from sqlalchemy.dialects.mysql import DATETIME

class YourModel(Base):
    __tablename__ = 'your_table'
    id = Column(Integer, primary_key=True)
    created_at = Column(DATETIME(fsp=3))

2. 检查数据库驱动配置

不同驱动对小数秒的处理逻辑有差异,以pymysql为例,确保连接URL未禁用小数秒支持(默认已开启,无需额外参数,但需保证驱动版本兼容):

from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://username:password@localhost/db_name?charset=utf8mb4')

3. 正确查看datetime的完整精度

Python的datetime对象本身存储了完整精度信息,只是默认打印时会省略末尾的零。可以通过格式化输出验证:

obj = session.query(YourModel).first()
# 输出带毫秒的完整时间格式
print(obj.created_at.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

直接打印obj.created_at可能显示2022-08-22 11:18:00,但实际obj.created_at.microsecond属性会存储对应毫秒值(比如.000对应0,.123对应123000)。


内容的提问来源于stack exchange,提问作者thuc.ta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:30:53