Home  >  Article  >  Backend Development  >  python根据时间生成mongodb的ObjectId的方法

python根据时间生成mongodb的ObjectId的方法

WBOY
WBOYOriginal
2016-06-06 11:22:481436browse

本文实例讲述了python根据时间生成mongodb的ObjectId的方法。分享给大家供大家参考。具体分析如下:

mongodb的_id为ObjectId类型,ObjectId内是包含时间戳信息的,这样我们在保存数据的时候就不需要再单独记录一个添加时间了,如果需要按照时间查询,我们可以先把时间变化成可查询的ObjectId,再通过_id字段查询,由于mongodb的_id是主键,查询效率非常高。下面的函数给出了如何把时间换算成ObjectId,同时该函数还可以指定时间的偏移量,比如多少天前的时间。

代码如下:

def object_id_from_datetime(from_datetime=None,span_days=0,span_hours=0,span_minutes=0,span_seconds=0,span_weeks=0):
    '''根据时间手动生成一个objectid,此id不作为存储使用'''
    if not from_datetime:
        from_datetime = datetime.datetime.now()
    from_datetime = from_datetime + datetime.timedelta(days=span_days,hours=span_hours,minutes=span_minutes,weeks=span_weeks)
    return ObjectId.from_datetime(generation_time=from_datetime)

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn