使用 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)