美文网首页python技巧数据库
python时间与Objectid(mongodb)的相互转换

python时间与Objectid(mongodb)的相互转换

作者: 陆_志东 | 来源:发表于2018-08-14 18:15 被阅读0次

mongodb数据库在存储数据的时候如果不指定_id,默认为ObjectId
Object内部是含有时间戳的.所以在生成的时候也需要我们的datetime模块
这篇文章讲述了如何完成objectid 和时间之间的转换

通过时间生成objectid

生成ObjectId需要python中的bson模块

导包方式

from bson.objectid import ObjectId
import datetime

def general_obj_from_time(from_datetime=None,time_delta=None):
    if from_datetime is None or not isinstance(from_datetime,datetime.datetime):
        from_datetime = datetime.datetime.now()  # 时间元组
    if time_delta:  # time_delta 是datetime.timedelta 类型,可以进行时间的加减运算
        from_datetime = from_datetime + time_delta
    
    return ObjectId.from_datetime(from_datetime)

obj = general_obj_from_time()
print()

objectid生成时间

# 调用上面的方法生成一个objid
obj = general_obj_from_time()
time2 = obj.generation_time.timetuple()
# 不过要注意time2 是 time.struct_time类型的数据

相关文章

网友评论

    本文标题:python时间与Objectid(mongodb)的相互转换

    本文链接:https://www.haomeiwen.com/subject/funvbftx.html