Last active
February 13, 2019 21:48
-
-
Save turtlemonvh/05e530ddce98f0fecb91183834f3189c to your computer and use it in GitHub Desktop.
Generate bson object ids with a specific time in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Use to generate an oid in python with a specific time, but also including uniqueness. | |
Helpful for generating ids for data for old time periods for testing. | |
The 3 bytes for machine id and the 2 bytes for process id are zeroed out. | |
You need to update the value of `inc` to ensure you generate unique ids within a single second. | |
See the `_generate` method on the ObjectId class for more details: | |
https://github.com/mongodb/mongo-python-driver/blob/3.5.1/bson/objectid.py#L165 | |
""" | |
import binascii | |
import calendar | |
import datetime | |
import struct | |
dt = datetime.datetime(2015, 6, 15) | |
inc = 1 | |
# Saves the value as a string | |
oid = binascii.hexlify(struct.pack(">i", int(calendar.timegm(dt.timetuple()))) + b"\x00\x00\x00\x00\x00" + struct.pack(">i", inc % 0xFFFFFF)[1:4]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment