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
相关产品推荐
相关产品推荐

