【问题标题】:Convert MongoDB time to epoch time - Python将 MongoDB 时间转换为纪元时间 - Python
【发布时间】:2014-05-03 16:16:28
【问题描述】:

我有一个 objectid("5217a543dd99a6d9e0f74702") 的 mongodb 时间。

如何在 Python 中将其转换为纪元时间。 (UTC 时区和 EST 时区)

【问题讨论】:

    标签: python mongodb datetime time pymongo


    【解决方案1】:

    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>)
    

    【讨论】:

      【解决方案2】:

      您可以使用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,但同样的概念也适用

      【讨论】:

      • Python 2.7 中没有 ObjectId.getTimestamp()
      • 我没有使用 Python 和 MongoDb,但是使用 C# 驱动程序,我能够将 JSON 值反序列化为 DateTime 对象。
      猜你喜欢
      • 2012-01-30
      • 1970-01-01
      • 2017-06-01
      • 2010-09-12
      • 1970-01-01
      • 2012-09-06
      • 2012-08-12
      • 2019-04-09
      • 2018-05-28
      相关资源
      最近更新 更多