pymongo - 试图在pymongo中获取带有日期的对象ID
问题描述
import pymongo
import datetime
from pymongo import MongoClient
from bson.objectid import ObjectId
from time import gmtime, strftime
gen_time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
dummy_id = ObjectId.from_datetime(gen_time)
result = db["config"].find({"_id":{"$lt": dummy_id}})
print(result)
及其显示错误 AttributeError: 'str' object has no attribute 'utcoffset'
解决方案
您将字符串传递给ObjectId.from_datetime()
:
gen_time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
dummy_id = ObjectId.from_datetime(gen_time)
而文档说
传递包含 UTC 的原始日期时间实例,或已转换为 UTC 的感知实例。
你可能想要
dummy_id = ObjectId.from_datetime(datetime.utcnow())
(或者也许datetime.datetime.utcnow()
因为你只是在做import datetime
)
推荐阅读
- c++ - 无法接收无效电子邮件
- c++ - 按人员编号快速排序一组人员
- powerbi - 使用 RankX 函数计算每个实体 ID 每个会计年度的日期排名
- swift - UITabBarController viewDidLoad 未运行
- python - 如何使用外部应用程序从移动应用程序中抓取数据?
- laravel - 在 Cpanel 中托管 Laravel 不会运行应用程序
- vb.net - 有没有办法强制 NuGet 在管道执行期间恢复最新的包版本?
- reactjs - Typescript 使用最新的样式组件引发错误
- php - PHP通过文件搜索关键字(不区分大小写)?
- swift - SwiftUI SceneDelegate - 调用中参数'index'的contentView缺少参数