简体   繁体   English

检查mongodb中的日期时间对象是否为UTC格式,来自python

[英]Checking if a datetime object in mongodb is in UTC format or not from python

In mongodb , a field called joining_date appears as mongodb ,名为joining_date的字段显示为

"Sun Dec 19 2010 05:35:55 GMT+0000 (UTC)"

This as you see is a UTC date . 如您所见,这是一个UTC日期。

But the same field when accessed from pymongo appears as 但是当从pymongo访问时,相同的字段显示为

 datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)

From python i need to check that the date is in utc format or not. 从python我需要检查日期是否为utc格式。

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 ? 如何从datetime.datetime(2010, 12, 19, 5, 35, 55, 286000) Sun Dec 19 2010 05:35:55 GMT+0000 (UTC)取回原始字符串Sun Dec 19 2010 05:35:55 GMT+0000 (UTC) datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)或如何检查datetime.datetime(2010, 12, 19, 5, 35, 55, 286000)是否采用UTC格式?

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返回的datetime对象始终表示UTC的时间,就像存储在MongoDB中的日期总是存储为(即假设为)UTC。

pymongo can convert your datetime s automatically to be time zone aware if you set the tz_info flag to True when creating your Connection . 如果在创建Connection时将tz_info标志设置为True ,pymongo可以自动将datetime时间转换为时区。 You can then use datetime s astimezone() method to convert to another time zone if you wish. 然后,您可以使用datetimeastimezone()方法转换为另一个时区(如果您愿意)。

To quote the PyMongo documentation: 引用PyMongo文档:

All datetimes retrieved from the server (no matter what version of the driver you're using) will be naive and represent UTC. 从服务器检索的所有日期时间(无论您使用的是什么版本的驱动程序)都是天真的并且代表UTC。

ie v.tzinfo is None . v.tzinfo is None You would have been warned about this if you'd tried to convert them to another timezone: 如果您尝试将它们转换为另一个时区,您会收到警告:

>>> v.astimezone(pytz.timezone("US/Eastern"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime

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) . 但是,您可以通过执行datetime(v.year, v.month, v.day, v.hour, v.minute, v.second, v.microsecond, pytz.utc)来获取时区感知日期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: 在这种情况下,您的原始代码将起作用:

v = datetime(2010, 12, 19, 5, 35, 55, 286000, pytz.utc)
v.tzinfo == pytz.utc # Returns True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM