2014-03-25 92 views

回答

0

您可以使用ObjectId.getTimestamp()方法獲取objectid的時間戳部分作爲日期。

一旦你有Date對象,你可以調用任何Date方法來得到你想要的。在shell中,你可以只按下Tab鍵即可獲得所允許的所有方法的列表:

> var myid = new ObjectId() 
> myid 
ObjectId("5331ba8163083f9b26efb5b3") 
> var mytime = myid.getTimestamp() 
> mytime 
ISODate("2014-03-25T17:18:57Z") 
> mytime.<TAB> 
mytime.constructor   mytime.getUTCFullYear(
mytime.getDate(    mytime.getUTCHours(
mytime.getDay(    mytime.getUTCMilliseconds(
mytime.getFullYear(   mytime.getUTCMinutes(
mytime.getHours(    mytime.getUTCMonth(
mytime.getMilliseconds(  mytime.getUTCSeconds(
mytime.getMinutes(   mytime.getYear(
mytime.getMonth(    mytime.hasOwnProperty(
mytime.getSeconds(   mytime.propertyIsEnumerable(
mytime.getTime(    mytime.setDate(
mytime.getTimezoneOffset( mytime.setFullYear(
mytime.getUTCDate(   mytime.setHours(
mytime.getUTCDay(   mytime.setMilliseconds(

注:我不熟悉Python,但相同的概念也適用

+0

沒有ObjectId.getTimestamp()在Python 2.7 – Kishore

+0

我還沒有使用的Python和MongoDB但與C#驅動器,我能夠反序列化JSON值成DateTime對象。 – Nanda

0

ObjectId.generation_time給你當時的ObjectId生成,在UTC:

>>> from bson import ObjectId 
>>> ObjectId("5217a543dd99a6d9e0f74702").generation_time 
datetime.datetime(2013, 8, 23, 18, 9, 7, tzinfo=<bson.tz_util.FixedOffset object at 0x102920c90>) 

The documentation is here.

要轉換爲東部時間,安裝pytz和:

>>> import pytz 
>>> ny = pytz.timezone('America/New_York') 
>>> gt = ObjectId("5217a543dd99a6d9e0f74702").generation_time 
>>> ny.normalize(gt.astimezone(ny)) 
datetime.datetime(2013, 8, 23, 14, 9, 7, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)