Python: how to convert a MongoDB timestamp to the MySQL date format

In this article we will see how to convert a MongoDB timestamp to the MySQL date format with Python.

MongoDB timestamps use milliseconds when calculating dates, so the starting value must be divided by 1000 before converting it with Python.

from math import ceil
from datetime import datetime

def convert_mongo_ts_to_mysql_dt(mongo_ts):
    start_ts = int(mongo_ts)
    base_ts = ceil(mongo_ts / 1000)
    sql_dt_format = '%Y-%m-%d %H:%M:%S'
    return datetime.fromtimestamp(base_ts).strftime(sql_dt_format)

The above procedure for the DATETIME format also applies to the other MySQL date formats.

Back to top