Python 查询特定时区的mongodb datetime输出
我有一个相当基本的问题。 集合中条目的日期时间另存为Python 查询特定时区的mongodb datetime输出,python,mongodb,pymongo,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": 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小时?如果您使用的是C#,您可以申请
如果您使用的是Ruby,那么您必须自己减去日期(或者我不知道这种机制)
其他语言-不知道:-)检查pymongo返回的-datetime
对象始终表示UTC时间,就像MongoDB中存储的日期始终存储为(即假定为)UTC一样
如果在创建连接时将tz_info标志设置为True,pymongo可以自动将日期时间转换为时区感知。然后,如果愿意,您可以使用方法转换到另一个时区
例如,您可以将其用于时区,或者如果您只需要编写自己的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')