ObjectID簡介
mongo存儲的數據在沒有特別指定_id數據類型時,默認類型爲ObjectID
‘_id’: ObjectId(‘55717c9eb2c983c127000000’)
ObjectId is a 12-byte BSON type, constructed using:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
python處理方式
基本思路就是轉換成時間對象 ,然後處理.
objectid – Tools for working with MongoDB ObjectIds
Tools for working with MongoDB ObjectIds.
class bson.objectid.ObjectId(oid=None)
Initialize a new ObjectId.
從ObjectID生成時間對象
from bson.objectid import ObjectId
a = ObjectId('55717c9eb2c983c127000000')
a.generation_time.timetuple()
In [29]: a.generation_time.timetuple()
Out[29]: time.struct_time(tm_year=2015, tm_mon=6, tm_mday=5, tm_hour=10, tm_min=40, tm_sec=30, tm_wday=4, tm_yday=156, tm_isdst=0)
#到了這種格式就可以隨便處理了
In [30]: time.strftime("%Y-%m-%d %H:%M:%S",a.generation_time.timetuple())
Out[30]: '2015-06-05 10:40:30'
生成ObjectID
# 時間對象轉換
>>> gen_time = datetime.datetime(2010, 1, 1)
>>> dummy_id = ObjectId.from_datetime(gen_time)
>>> ObjectId(b'foo-bar-quux')
ObjectId('666f6f2d6261722d71757578')
>>> ObjectId('0123456789ab0123456789ab')
ObjectId('0123456789ab0123456789ab')
>>>
>>> # A u-prefixed unicode literal:
>>> ObjectId(u'0123456789ab0123456789ab')
ObjectId('0123456789ab0123456789ab')