检查 mongodb 中的日期时间对象是否为 UTC 格式
在 mongodb
中,名为 joining_date
的字段显示为
"Sun Dec 19 2010 05:35:55 GMT+0000 (UTC)"
This as you see is a UTC date 。
但是从 pymongo 访问时,同一字段显示为“
datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)
从 python 我需要检查日期是否采用 utc 格式”。
问题:我得到一个奇怪的结果,如下所示
v = datetime(2010, 12, 19, 5, 35, 55, 286000)
v.tzinfo == pytz.utc # Returns False !..why ?
如何从 datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)
或者我如何检查是否datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)
是否采用 UTC 格式?
In mongodb
, a field called joining_date
appears as
"Sun Dec 19 2010 05:35:55 GMT+0000 (UTC)"
This as you see is a UTC date .
But the same field when accessed from pymongo appears as
datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)
From python i need to check that the date is in utc format or not.
Problem: I get a strange result as shown below
v = datetime(2010, 12, 19, 5, 35, 55, 286000)
v.tzinfo == pytz.utc # Returns False !..why ?
How can I get back the original string Sun Dec 19 2010 05:35:55 GMT+0000 (UTC)
from datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)
or how can I check if datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)
is in UTC format or not ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
pymongo 返回的 datetime 对象始终表示 UTC 时间,就像存储在 MongoDB 中的日期始终存储为(即假定为)UTC 格式一样。
如果您在创建
连接tz_info
标志设置为True
,pymongo可以自动将您的datetime
转换为时区感知。代码>.然后,如果您愿意,可以使用datetime
的astimezone()
方法转换为另一个时区。datetime
objects returned by pymongo always represent a time in UTC, just as dates stored in MongoDB are always stored as (that is, assumed to be in) UTC.pymongo can convert your
datetime
s automatically to be time zone aware if you set thetz_info
flag toTrue
when creating yourConnection
. You can then usedatetime
sastimezone()
method to convert to another time zone if you wish.引用 PyMongo 文档:
即
v.tzinfo 为 None
。如果您尝试将它们转换为另一个时区,您会收到警告:但是,您可以通过执行
datetime(v.year, v.month, v.day, v.hour) 获得时区感知日期时间,v.分钟,v.秒,v.微秒,pytz.utc)
。在这种情况下,您的原始代码将起作用:To quote the PyMongo documentation:
i.e.
v.tzinfo is None
. You would have been warned about this if you'd tried to convert them to another timezone:However, you can get a timezone aware datetime by doing
datetime(v.year, v.month, v.day, v.hour, v.minute, v.second, v.microsecond, pytz.utc)
. In this case, your original code would work: