使用 PyMongo 的 ObjectId 生成 ID

创建日期: 2025-05-14 19:04 | 作者: 风波 | 浏览次数: 4 | 分类: Python

使用 mongodb 官方的 python driver 生成 ObjectId

from bson.objectid import ObjectId

# 生成新的 ObjectId
new_id = ObjectId()
print(new_id)

# 验证 ObjectId
print(ObjectId.is_valid(str(new_id)))
print(ObjectId.is_valid("invalidid"))

从其中解析生成时间

from bson.objectid import ObjectId

oid_str = "507f1f77bcf86cd799439011"  # 示例 ObjectId
oid = ObjectId(oid_str)

# 各种时间格式输出
print("ISO format:", oid.generation_time.isoformat())
print("Custom format:", oid.generation_time.strftime("%Y-%m-%d %H:%M:%S"))
print("Date only:", oid.generation_time.date())
print("Year:", oid.generation_time.year)
print("Month:", oid.generation_time.month)
print("Day:", oid.generation_time.day)
4 浏览
8 爬虫
0 评论