Extract the time from a UUID v1 in python Extract the time from a UUID v1 in python python python

Extract the time from a UUID v1 in python


Looking inside /usr/lib/python2.6/uuid.py you'll see

def uuid1(node=None, clock_seq=None):    ...    nanoseconds = int(time.time() * 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

solving the equations for time.time(), you'll get

time.time()-like quantity = ((timestamp - 0x01b21dd213814000L)*100/1e9)

So use:

In [3]: import uuidIn [4]: u = uuid.uuid1()In [58]: datetime.datetime.fromtimestamp((u.time - 0x01b21dd213814000L)*100/1e9)Out[58]: datetime.datetime(2010, 9, 25, 17, 43, 6, 298623)

This gives the datetime associated with a UUID generated by uuid.uuid1.


Or just use the TimeUUID library, so that you know you didn't get the math wrong

Example

import uuidimport time_uuidmy_uuid = uuid.UUID('{12345678-1234-5678-1234-567812345678}')ts = time_uuid.TimeUUID(bytes=my_uuid.bytes).get_timestamp()


You could use a simple formula that follows directly from the definition:

The timestamp is a 60-bit value. For UUID version 1, this isrepresented by Coordinated Universal Time (UTC) as a count of 100-nanosecond intervals since 00:00:00.00, 15 October 1582 (the date ofGregorian reform to the Christian calendar).

>>> from uuid import uuid1>>> from datetime import datetime, timedelta>>> datetime(1582, 10, 15) + timedelta(microseconds=uuid1().time//10)datetime.datetime(2015, 11, 13, 6, 59, 12, 109560)