Romain G
Romain G

Reputation: 1346

Create timezone-aware ISODate with pymongo

I'm looking for a way to store a timezone-aware datetime object in mongoDB.

I read here: Create an ISODate with pyMongo that storing a datetime object in MongoDB with pymongo will result in a ISODate object being stored (or an object that looks like this when querying from the shell)

Using the datetime.replace(tzinfo=[...]) method, there is a way to make the datetime object aware of its timezone. Unfortunately, when storing such object in mongoDB, the timezone information seems to be lost.

My question is: is there a way to store the timezone in the ISODate object itself, so that it looks like something like this: ISODate("2012-07-14T01:00:00+01:00") when querying the shell and so that the datetime object is still timezone aware when reloaded with pymongo later on?

Thanks a lot for your help!

Upvotes: 4

Views: 5157

Answers (2)

tnusraddinov
tnusraddinov

Reputation: 750

from datetime import datetime
from dateutil.tz import *

def to_utc(date_time):
    return date_time.replace(tzinfo=tzlocal()).astimezone(tzoffset(None, 0))

Upvotes: 0

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241900

No, there's not a way to do that. MongoDB's ISODate is just a wrapper around a Date object, which is just a moment in time represented by an integer corresponding to the number of milliseconds elapsed since Jan 1, 1970 UTC. There is no way for it to retain an offset.

You might consider storing it just as a string, perhaps in a secondary field so you can still query for that moment in time while still knowing the local time and offset.

Also, assuming you're using tzdb time zones from either pytz or dateutil, such as "Europe/London", you should recognize that there's no way to determine a time zone from just an offset. So if you really need to reconstruct a full tz aware datetime, then you'll also have to store the time zone identifier in a separate field.

Upvotes: 5

Related Questions