How to correctly handle datetime?

As far as I know, MongoDB requires that datetimes are expressed as UTC in ISO format.
So, if I want to store a DateTime in MongoDB, I have to use a code similar to:

result = db.objects.insert_one(
… {“last_modified”: datetime.datetime.utcnow()})
In the same way, in “find” queries I have to express datetimes in UTC while eventually, show printed results into the locale.
Is this correct?
Does it exist a better way to automatically handle UTC to locale (taking into account also daylight saving time)?

Hi @Sergio_49057,

In MongoDB, we use BSON date type in UTC datetime. I believe the idea behind this is to avoid multiple confusions and to handle worldwide datetime in an easy way. Here is a great video explaining all the issues with timezones. :slight_smile: It helped me understand why we have UTC timezone: video link

Applications that require datetime to be stored with timezone or in specific date format, we must save the datetime in UTC format in MongoDB. When retrieving back to show to the user, we need to convert it back to local timezone in application logic.

These links might help you:


1 Like