Skip to content

Instantly share code, notes, and snippets.

@eXenon
Created October 26, 2016 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eXenon/b932e4329dd108a299f1b1148c23c887 to your computer and use it in GitHub Desktop.
Save eXenon/b932e4329dd108a299f1b1148c23c887 to your computer and use it in GitHub Desktop.
def make_id(mongo_id: ObjectId, date=None, iteration=0):
target_date = date or mongo_id.generation_time.replace(tzinfo=None)
hasher = hashlib.sha1()
hasher.update(mongo_id.binary)
hasher.update(str(iteration).encode())
hash = hasher.digest()
time = int((target_date - datetime(1582, 10, 15)).total_seconds() * 10000000)
time_low = time & 0xffffffff
time_mid = (time >> 32) & 0xffff
time_high = ((time >> 48) & 0x0fff) | 0x1000
clock_seq_hi_variant = hash[0]
# set variant to RFC 4122
clock_seq_hi_variant &= ~0xc0
clock_seq_hi_variant |= 0x80
clock_seq_low = hash[1]
node = int.from_bytes(hash[2:8], byteorder='big')
return uuid.UUID(fields=(time_low, time_mid, time_high, clock_seq_hi_variant, clock_seq_low, node))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment