【发布时间】:2014-05-03 16:16:28
【问题描述】:
我有一个 objectid("5217a543dd99a6d9e0f74702") 的 mongodb 时间。
如何在 Python 中将其转换为纪元时间。 (UTC 时区和 EST 时区)
【问题讨论】:
标签: python mongodb datetime time pymongo
我有一个 objectid("5217a543dd99a6d9e0f74702") 的 mongodb 时间。
如何在 Python 中将其转换为纪元时间。 (UTC 时区和 EST 时区)
【问题讨论】:
标签: python mongodb datetime time pymongo
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>)
要转换为东部时间,请安装 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>)
【讨论】:
您可以使用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,但同样的概念也适用
【讨论】: