Extract the time from a UUID v1 in python

时光总嘲笑我的痴心妄想 提交于 2019-11-28 06:29:24

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.

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)

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

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!