Skip to content

Instantly share code, notes, and snippets.

@mezhaka
Created April 19, 2021 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mezhaka/8dea8433fc6d04017160c8344984669d to your computer and use it in GitHub Desktop.
Save mezhaka/8dea8433fc6d04017160c8344984669d to your computer and use it in GitHub Desktop.
# A snippet to show that pymongo / mongo converts timezone aware datetime objects to UTC, when saving.
# docker run --env MONGO_INITDB_DATABASE=brain --env MONGO_INITDB_ROOT_USERNAME=root --env MONGO_INITDB_ROOT_PASSWORD=secret --publish-all mongo:4.2
#
# lookup which port it was mapped to:
# $ docker container ls
# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
# 8eaf2dd5aedb mongo:4.2 "docker-entrypoint.s…" 6 minutes ago Up 6 minutes 0.0.0.0:55000->27017/tcp brave_moser
import datetime
import pymongo
import pytz
ts = datetime.datetime.fromisoformat("2021-04-19 17:01:50.221").replace(tzinfo=pytz.timezone("UTC"))
btz = pytz.timezone("Europe/Berlin")
c = pymongo.MongoClient("localhost:55000", username="root", password="secret")
c.get_database("db").get_collection("col").drop()
# Insert with "Europe/Berlin"
c.get_database("db").get_collection("col").insert_one({"d": btz.normalize(ts)})
inserted = next(iter(c.get_database("db").get_collection("col").find()))
# Observe inserted is in UTC:
print(f"inserted: {inserted['d']}, utc: {ts}, Berlin: {btz.normalize(ts)}")
# inserted: 2021-04-19 17:01:50.221000, utc: 2021-04-19 17:01:50.221000+00:00, Berlin: 2021-04-19 19:01:50.221000+02:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment