首页 > 解决方案 > 试图在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'

标签: pymongo

解决方案


您将字符串传递给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


推荐阅读