查询mongodb datetime输出为特定时区

Ris*_*ran 4 python mongodb pymongo

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

    "lastUpdated": ISODate("2011-12-07T02:46:51.101Z")
Run Code Online (Sandbox Code Playgroud)

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

    db.Collection.find({Type: 'Reports', patId: 'JOHNSONGARY'}, 
                       {'lastUpdated': 1} )
Run Code Online (Sandbox Code Playgroud)

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

    str(mongo_documents['lastUpdated'].strftime('%Y-%m-%d %H:%M:%S'))
Run Code Online (Sandbox Code Playgroud)

如何在此命令中扣除5个小时?

Ros*_*oss 6

查看文档 - datetimepymongo返回的对象始终表示UTC时间,就像MongoDB中存储的日期始终存储为(即假设为)UTC

如果在创建Connection时将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()
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

# 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')
Run Code Online (Sandbox Code Playgroud)