James
James

Reputation: 51

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 ?

Upvotes: 5

Views: 5452

Answers (2)

dcrosta
dcrosta

Reputation: 26258

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.

Upvotes: 11

Matthew Wilkes
Matthew Wilkes

Reputation: 1088

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

Upvotes: 1

Related Questions