Python's method for generating mongodb's ObjectId based on time

  • 2020-04-02 14:39:30
  • OfStack

This article illustrates python's method of generating mongodb's ObjectId based on time. Share with you for your reference. Specific analysis is as follows:

Mongo _id for ObjectId type, is contained within the ObjectId timestamp information, so that we at the time of saving data do not need to separate records a add any more time, if you need to query in accordance with the time, we could start with the time change into can query the ObjectId, again through the query _id field, due to the mongo _id is a primary key, the query efficiency is very high. The following function shows how to convert time to the ObjectId, and also specifies the offset of time, such as how many days ago.

def object_id_from_datetime(from_datetime=None,span_days=0,span_hours=0,span_minutes=0,span_seconds=0,span_weeks=0):
    ''' Manually generate one based on time objectid , this id Not used as storage '''
    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)

I hope this article has helped you with your Python programming.


Related articles: