Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 712
James Avatar asked Jul 27 '11 15:07

James


2 Answers

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 datetimes automatically to be time zone aware if you set the tz_info flag to True when creating your Connection. You can then use datetimes astimezone() method to convert to another time zone if you wish.

like image 89
dcrosta Avatar answered Oct 23 '22 06:10

dcrosta


To quote the PyMongo documentation:

All datetimes retrieved from the server (no matter what version of the driver you’re using) will be naive and represent UTC.

i.e. 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). 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
like image 23
MatthewWilkes Avatar answered Oct 23 '22 08:10

MatthewWilkes