我有一个相当基本的问题。 集合中条目的日期时间保存为
"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个小时?
答案 0 :(得分:6)
查看pymongo返回的documentation - datetime
对象始终表示UTC时间,就像存储在MongoDB中的日期始终存储为(即假设为)UTC
例如,您可以将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)