使用mongodb自带的ObjectID获取记录生成时间

有些时候,我们在写入mongo数据的时候,可能需要记录这条数据的插入时间,我们一般情况下回给记录增加一个 create_time。 实际上,如果我们插入的数据含有 ObjectId 的话,那么其实这个id是包含了生成时间的,同时也可以作为记录的主键,一举多得。 以python为例,我们有这样一条记录: document = { "_id": ObjectId("5dfc8ac5d3fa12967b8888ec"), "user": "mike", "age": 19, } 这时候,我们可以使用ObjectId自带的generation_time属性,获取这条记录的插入时间: time = ObjectId("5dfc8ac5d3fa12967b8888ec").generation_time print(time) 输出: datetime.datetime(2019, 12, 20, 8, 48, 5, tzinfo=<bson.tz_util.FixedOffset object at 0x7f874030f9a0>) 需要注意到的是,里面的时区信息,显示的是一个 FixedOffset,即固定偏移,我们看 generation_time 属性的定义: utc = FixedOffset(0, "UTC") """Fixed offset timezone representing UTC.""" class ObjectId(object): # ... 省略其他代码 ... @property def generation_time(self): """A :class:`datetime.datetime` instance representing the time of generation for this :class:`ObjectId`....

June 1, 2022 · 1 min · LingZihuan