Skip to content

Instantly share code, notes, and snippets.

@eevans
Created September 29, 2010 18:26
Show Gist options
  • Select an option

  • Save eevans/603252 to your computer and use it in GitHub Desktop.

Select an option

Save eevans/603252 to your computer and use it in GitHub Desktop.
"""
Derived from the uuid module in standard lib.
"""
from uuid import UUID, getnode
import time, random
def uuid1(timestamp=None):
"""
Generate a type 1 UUID from a timestamp, (or the current time).
"""
if timestamp is None: nanoseconds = int(time.time() * 1e9)
else: nanoseconds = int(timestamp * 1e9)
# 0x01b21dd213814000 is the number of 100-ns intervals between the
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
timestamp = int(nanoseconds//100) + 0x01b21dd213814000L
clock_seq = random.randrange(1<<14L) # instead of stable storage
time_low = timestamp & 0xffffffffL
time_mid = (timestamp >> 32L) & 0xffffL
time_hi_version = (timestamp >> 48L) & 0x0fffL
clock_seq_low = clock_seq & 0xffL
clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
node = getnode()
return UUID(fields=(time_low, time_mid, time_hi_version,
clock_seq_hi_variant, clock_seq_low, node), version=1)
def datetime_for_uuid1(uuid):
"""
Return a Python datetime for a type 1 UUID.
"""
from datetime import datetime
# 0x01b21dd213814000 is the number of 100-ns intervals between the
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
nanos = ((uuid.get_time() - 0x01b21dd213814000L) * 1e2)
return datetime.fromtimestamp(nanos / 1e9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment