Skip to content

Pymongo - Save local time

Spent a while with this thing and came to know that even if you convert datetime to your local timezone MongoDB converts it back to UTC while saving.

How to convert to local timezone ?

from datetime import datetime
from dateutil import tz

utctime = datetime.now()
localtime = utctime.replace(tzinfo=tz.gettz('UTC')).astimezone(tz.gettz('Asia/Kolkata'))

So, the only way that MongoDB would know that it is in the form of IST is by timezone info inside datetime object.

Updating local time in MongoDB ?

mongodb.chat.update(
    {'id': 1},
    {"$set": {'date': localtime.replace(tzinfo=None)}}
)

By removing timezone information from the datetime object (also known as naive datetime in python), you are enforcing mongo by saying - This is the UTC time !