Timezone aware datetime in mongodb using pymongo

MongoDB stores dates in UTC timezone by default. This makes it possible to do timezone conversion to be done in both client side side or server side.


$ pip install pytz pymongo


from pymongo import MongoClient
from datetime import datetime
from bson.codec_options import CodecOptions
import pytz

client = MongoClient('mongodb://localhost:27017/')
db = client['test_db']
timezone = pytz.timezone('Asia/Calcutta')

## insert a document with createdat
insert_doc = db.playground.insert_one({"createdat": datetime.utcnow()})

playground_collection = db.playground.with_options(codec_options=CodecOptions(tz_aware=True, tzinfo=timezone))
document = playground_collection.find_one()

# Timezone aware datetime
# prints 'createdat': datetime.datetime(2018, 1, 6, 9, 49, 50, 35000, tzinfo=<DstTzInfo 'Asia/Calcutta' IST+5:30:00 STD>)