查询mongodb datetime输出为特定时区

时间:2012-01-05 06:53:26

标签: python mongodb pymongo

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

    "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个小时?

2 个答案:

答案 0 :(得分:6)

查看pymongo返回的documentation - datetime对象始终表示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()

然后你可以这样做:

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

答案 1 :(得分:0)

如果您使用的是C#,则可以应用this answer

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

其他语言 - 不知道: - )