cdecker cdecker - 1 year ago 143
Python Question

Extract the time from a UUID v1 in python

I have some UUIDs that are being generated in my program at random, but I want to be able to extract the timestamp of the generated UUID for testing purposes. I noticed that using the

accessor I can get the various parts of the timestamp but I have no idea on how to combine them.

Answer Source

Looking inside /usr/lib/python2.6/ I 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(), we get

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

So I try:

In [3]: import uuid

In [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)

So this seems to give the datetime associated with a UUID generated by uuid.uuid1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download