MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / from_datetime

Method from_datetime

bson/objectid.py:123–153  ·  view source on GitHub ↗

Create a dummy ObjectId instance with a specific generation time. This method is useful for doing range queries on a field containing :class:`ObjectId` instances. .. warning:: It is not safe to insert a document containing an ObjectId generated using t

(cls: Type[ObjectId], generation_time: datetime.datetime)

Source from the content-addressed store, hash-verified

121
122 @classmethod
123 def from_datetime(cls: Type[ObjectId], generation_time: datetime.datetime) -> ObjectId:
124 """Create a dummy ObjectId instance with a specific generation time.
125
126 This method is useful for doing range queries on a field
127 containing :class:`ObjectId` instances.
128
129 .. warning::
130 It is not safe to insert a document containing an ObjectId
131 generated using this method. This method deliberately
132 eliminates the uniqueness guarantee that ObjectIds
133 generally provide. ObjectIds generated with this method
134 should be used exclusively in queries.
135
136 `generation_time` will be converted to UTC. Naive datetime
137 instances will be treated as though they already contain UTC.
138
139 An example using this helper to get documents where ``"_id"``
140 was generated before January 1, 2010 would be:
141
142 >>> gen_time = datetime.datetime(2010, 1, 1)
143 >>> dummy_id = ObjectId.from_datetime(gen_time)
144 >>> result = collection.find({"_id": {"$lt": dummy_id}})
145
146 :param generation_time: :class:`~datetime.datetime` to be used
147 as the generation time for the resulting ObjectId.
148 """
149 oid = (
150 _PACK_INT(_datetime_to_millis(generation_time) // 1000)
151 + b"\x00\x00\x00\x00\x00\x00\x00\x00"
152 )
153 return cls(oid)
154
155 @classmethod
156 def is_valid(cls: Type[ObjectId], oid: Any) -> bool:

Callers 1

test_from_datetimeMethod · 0.80

Calls 1

_datetime_to_millisFunction · 0.90

Tested by 1

test_from_datetimeMethod · 0.64