Python's method of generating MongoDB Objectid based on time _python

Source: Internet
Author: User
Tags add time mongodb

The example in this article describes how Python generates MongoDB Objectid based on time. Share to everyone for your reference. The specific analysis is as follows:

MongoDB _id for the Objectid type, Objectid contains timestamp information, so that we save the data when there is no need to record a separate add time, if you need to query according to time, we can change the time to query the Objectid, and then through _ ID field query, because the MongoDB _id is the primary key, query efficiency is very high. The following function shows how to convert time to Objectid, and the function can also specify the offset of time, such as how many days ago.

Copy Code code as follows:
def object_id_from_datetime (From_datetime=none,span_days=0,span_hours=0,span_minutes=0,span_seconds=0,span_ Weeks=0):
"" To generate a Objectid manually based on time, this ID is 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 will help you with your Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.