Skip to content

Commit b35cec3

Browse files
author
Mike Dirolf
committed
add generation_time property to ObjectId instances
1 parent a05b159 commit b35cec3

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

pymongo/objectid.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
"""Representation of an ObjectId for Mongo."""
1616

17+
import datetime
1718
import threading
1819
import types
1920
import time
@@ -159,9 +160,21 @@ def get_binary(self):
159160
"""Get the binary representation of this ObjectId.
160161
"""
161162
return self.__id
162-
163163
binary = property(get_binary)
164164

165+
def generation_time(self):
166+
"""A :class:`datetime.datetime` instance representing the time of
167+
generation for this :class:`ObjectId`.
168+
169+
The :class:`datetime.datetime` is always naive and represents the
170+
generation time in UTC. It is precise to the second.
171+
172+
.. versionadded:: 1.1.2+
173+
"""
174+
t = struct.unpack(">i", self.__id[0:4])[0]
175+
return datetime.datetime.utcfromtimestamp(t)
176+
generation_time = property(generation_time)
177+
165178
def __str__(self):
166179
return self.__id.encode("hex")
167180

test/test_objectid.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
"""Tests for the objectid module."""
1616

17+
import datetime
1718
import unittest
1819
import sys
1920
sys.path[0:0] = [""]
@@ -104,6 +105,11 @@ def test_multiprocessing(self):
104105
self.assert_(id not in map)
105106
map[id] = True
106107

108+
def test_generation_time(self):
109+
d1 = datetime.datetime.utcnow()
110+
d2 = ObjectId().generation_time
111+
112+
self.assert_(d2 - d1 < datetime.timedelta(seconds = 2))
107113

108114
if __name__ == "__main__":
109115
unittest.main()

0 commit comments

Comments
 (0)