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

使用ISODate查询pymongo时报'str' object is not callable错误如何解决

问题产生原因
  • 代码中'ISODate'('2021-09-01')写法存在语法错误:ISODate被引号包裹后成为字符串类型,字符串无法被当作函数调用,直接触发了TypeError: 'str' object is not callable报错。
  • ISODate()是MongoDB原生Shell的专属语法,不适用于pymongo开发场景,即使去掉引号直接调用ISODate()也会出现名称未定义的错误。
解决方法

pymongo会自动将Python标准库的datetime对象转换为MongoDB兼容的ISODate格式做匹配,不需要使用ISODate相关语法,正确写法如下:

from datetime import datetime

# 构造查询条件
query = {'createdAt': {'$gt': datetime(2021, 9, 1)}}
cursor = col.find(query)

如果MongoDB中存储的createdAt字段带有时区属性,需要构造对应时区的datetime对象查询,示例(使用pytz处理UTC时区):

from datetime import datetime
import pytz

query = {'createdAt': {'$gt': datetime(2021, 9, 1, tzinfo=pytz.UTC)}}
cursor = col.find(query)

内容的提问来源于stack exchange,提问作者meltedhead

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:15:03