Extract the time from a UUID v1 in python

2019-01-17 08:17发布

问题:

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 fields accessor I can get the various parts of the timestamp but I have no idea on how to combine them.

回答1:

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

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



回答2:

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

The timestamp is a 60-bit value. For UUID version 1, this is represented by Coordinated Universal Time (UTC) as a count of 100- nanosecond intervals since 00:00:00.00, 15 October 1582 (the date of Gregorian 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)


回答3:

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

Example

import uuid
import time_uuid

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


回答4:

Since I have Cassandra installed and I am using this with Cassandra I was able to use the datetime_from_uuid1 from cassandra.util

>>> import uuid
>>> from cassandra.util import datetime_from_uuid1
>>> foo = uuid.uuid1()
>>> dt_foo = datetime_from_uuid1(foo)
>>> dt_foo
datetime.datetime(2016, 07, 26, 8, 2, 12, 104560)