Datetimes and Timezones

    PyMongo uses datetime.datetime objects for representing dates and times in MongoDB documents. Because MongoDB assumes that dates and times are in UTC, care should be taken to ensure that dates and times written to the database reflect UTC. For example, the following code stores the current UTC date and time into MongoDB:

    1. ... {"last_modified": datetime.datetime.now()})

    The value for last_modified is very different between these two examples, even though both documents were stored at around the same local time. This will be confusing to the application that reads them:

    1. >>> result = db.tzdemo.insert_one(
    2. >>> db.tzdemo.find_one()['date']
    3. datetime.datetime(2002, 10, 27, 6, 0)
    4. >>> db.get_collection('tzdemo', codec_options=options).find_one()['date']
    5. datetime.datetime(2002, 10, 27, 6, 0,
    6. tzinfo=<bson.tz_util.FixedOffset object at 0x10583a050>)

    When storing objects that specify a timezone (i.e. they have a tzinfo property that isn’t None), PyMongo will convert those datetimes to UTC automatically:

    PyMongo 3.1 introduced a tzinfo property that can be set on CodecOptions to convert objects to local time automatically. For example, if we wanted to read all times out of MongoDB in US/Pacific time:

    1. datetime.datetime(2002, 10, 27, 14, 0)
    2. >>> aware_times = db.times.with_options(codec_options=CodecOptions(
    3. ... tz_aware=True,
    4. ... tzinfo=pytz.timezone('US/Pacific')))
    5. >>> result = aware_times.find_one()
    6. tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)