查询MongoDB日期时间输出为特定时区
我有一个比较基础的问题。一个集合中的条目的日期时间是以
"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
7
可以查看一下文档 - pymongo返回的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')