views:

69

answers:

1

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.

+3  A: 

Looking inside /usr/lib/python2.6/uuid.py 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.

unutbu
Looks like you solved my problem. In the meantime I had to go back and create my own constructor since it was generating only the current timestamps, and I needed random past timestamps. Thanks for your quick answer :-)
cdecker