gpt4 book ai didi

python - 查询特定时区的 mongodb 日期时间输出

转载 作者:可可西里 更新时间:2023-11-01 09:11:50 26 4
gpt4 key购买 nike

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

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

最佳答案

查看 documentation - 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')

关于python - 查询特定时区的 mongodb 日期时间输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8738719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com