【问题标题】:Query mongodb datetime output to be for certain timezone查询 mongodb 日期时间输出为特定时区
【发布时间】:2012-01-05 06:53:26
【问题描述】:

我有一个相当基本的问题。 集合中条目的日期时间保存为

    "lastUpdated": ISODate("2011-12-07T02:46:51.101Z")

GMT 格式。如何查询条目以便我得到的查询输出是 EST 格式? 这可能在查询本身中还是我必须手动减去 5 小时(ESt = -5.00 小时)? 我使用的查询是;

    db.Collection.find({Type: 'Reports', patId: 'JOHNSONGARY'}, 
                       {'lastUpdated': 1} )

编辑: 我使用 python 进行查询,并且正在使用返回的时间戳;

    str(mongo_documents['lastUpdated'].strftime('%Y-%m-%d %H:%M:%S'))

这个命令怎么扣5小时?

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    查看 pymongo 返回的 documentation - datetime 对象始终表示 UTC 时间,就像存储在 MongoDB 中的日期始终存储为(即假定为)UTC 一样

    如果您在创建连接时将 tz_info 标志设置为 True,pymongo 可以自动将您的日期时间转换为时区感知。然后,您可以根据需要使用datetime.astimezone() 方法转换到另一个时区。

    因此,例如,您可以将pytz 用于时区,或者如果您只需要 EST 自己编写:

    import datetime
    
    class Eastern(datetime.tzinfo):
    
        def utcoffset(self, dt):
          return datetime.timedelta(hours=-5)
    
        def tzname(self, dt): 
            return "EST"
    
        def dst(self, dt):
            return datetime.timedelta(0)
    
    
    EST = Eastern()
    

    那么你可以这样做:

    # Get now for EST
    now = datetime.datetime.now(EST)
    print now.strftime('%Y-%m-%d %H:%M:%S')
    
    from pymongo import Connection
    # Create a timezone aware connection
    connection = Connection('localhost', 27017, tz_aware=True)
    
    # Save your data
    db = connection.test_database
    db.stackoverflow.save({"Type": "reports", "patId": 'JOHNSONGARY', "lastUpdated": now})
    
    doc = db.stackoverflow.find()[0]
    print doc['lastUpdated'].astimezone(EST).strftime('%Y-%m-%d %H:%M:%S')
    
    # Confirm they are the same
    assert doc['lastUpdated'].astimezone(EST).strftime('%Y-%m-%d %H:%M:%S') == now.strftime('%Y-%m-%d %H:%M:%S')
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 C#,您可以申请 this answer

      如果您使用的是 Ruby,那么您必须自己减去日期(或者我不知道这种机制)。

      其他语言 - 不知道 :-)

      【讨论】:

        猜你喜欢
        • 2022-01-17
        • 1970-01-01
        • 2011-05-03
        • 2012-08-11
        • 1970-01-01
        • 2014-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多