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

FastAPI写入MongoDB时CET时间戳报错:datetime.datetime不可调用

解决Pydantic中timestamp字段的'datetime.datetime' object is not callable错误

修正后的代码

from datetime import datetime, timedelta
from pydantic import BaseModel, Field
from bson.objectid import ObjectId as PyObjectId

class DataModel(BaseModel):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    loc: str
    sensor: str
    temp: float
    humi: float
    press: float
    power: float
    timestamp: datetime = Field(default_factory=lambda: datetime.utcnow() + timedelta(hours=1))

    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {PyObjectId: str}

问题原因

default_factory 要求传入可调用对象(函数、类等),Pydantic会在生成默认值时调用它。你之前的写法 datetime.utcnow() + timedelta(hours=1) 是直接计算出一个具体的datetime对象,而非可调用的函数。当Pydantic尝试调用这个对象时,自然会抛出'datetime.datetime' object is not callable错误。

而datetime.utcnow(不带括号)是函数本身,符合default_factory的要求,所以能正常运行,但无法实现时区偏移的需求。

进阶优化(处理夏令时)

如果需要严格遵循CET时区(含夏令时切换),推荐使用zoneinfo(Python 3.9+内置)模块,避免固定偏移的局限性:

from zoneinfo import ZoneInfo

# 替换timestamp字段的default_factory
timestamp: datetime = Field(default_factory=lambda: datetime.now(tz=ZoneInfo("Europe/Paris")))

内容的提问来源于stack exchange,提问作者Marc Müller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:20:34