Skip to content

Instantly share code, notes, and snippets.

@abatilo
Created June 1, 2019 03:56
Show Gist options
  • Save abatilo/c08793721c3148932df7d64da89560f7 to your computer and use it in GitHub Desktop.
Save abatilo/c08793721c3148932df7d64da89560f7 to your computer and use it in GitHub Desktop.
Time based uuid
import random
from datetime import datetime, timezone
BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(num, alphabet=BASE62):
"""Encode a positive number in Base X
Arguments:
- `num`: The number to encode
- `alphabet`: The alphabet to use for encoding
"""
base = len(alphabet)
if num < base:
return alphabet[num]
arr = []
while num:
num, rem = divmod(num, base)
arr.append(alphabet[rem])
arr.reverse()
return ''.join(arr)
epoch_bits = 33 # 2 ** 33 seconds == 272 years
fill_bits = 64 - epoch_bits
def guid():
# epoch = datetime.utcfromtimestamp(1559355764)
epoch = datetime(2017, 9, 9, tzinfo=timezone.utc)
now = datetime.fromtimestamp(datetime.utcnow().timestamp(), tz=timezone.utc)
rand_timestamp = f'{int((now - epoch).total_seconds() * 1000):b}'.zfill(epoch_bits)[:epoch_bits]
# print(rand_timestamp)
rand_bits = f'{random.getrandbits(fill_bits):b}'
zfill = rand_bits.zfill(fill_bits)
sixty_four = rand_timestamp + zfill
return encode(int(sixty_four, 2))
loops = 0
avg = 0
while True:
uniq = set()
count = 0
while len(uniq) == count:
count += 1
# uniq.add(random.getrandbits(23))
g = guid()
uniq.add(g)
# print(g)
loops += 1
print(count)
avg += count
print(avg / loops)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment