How do I create a datetime in Python from milliseconds?

PythonDatetime

Python Problem Overview


How do I create a datetime in Python from milliseconds? I can create a similar Date object in Java by java.util.Date(milliseconds).

> Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Python Solutions


Solution 1 - Python

Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)

Solution 2 - Python

What about this? I presume it can be counted on to handle dates before 1970 and after 2038.

target_datetime_ms = 200000 # or whatever
base_datetime = datetime.datetime(1970, 1, 1)
delta = datetime.timedelta(0, 0, 0, target_datetime_ms)
target_datetime = base_datetime + delta

as mentioned in the Python standard lib:

> fromtimestamp() may raise ValueError, if the timestamp is out of the > range of values supported by the platform C localtime() or gmtime() > functions. It’s common for this to be restricted to years in 1970 > through 2038.

Very obviously, this can be done in one line:

target_dt = datetime(1970, 1, 1) + timedelta(milliseconds=target_dt_ms)

Solution 3 - Python

Converting millis to datetime (UTC):

import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)

Converting datetime to string following the RFC3339 standard (used by Open API specification):

from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z

Solution 4 - Python

Bit heavy because of using pandas but works:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()

Solution 5 - Python

import pandas as pd

Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshuaView Question on Stackoverflow
Solution 1 - PythonvartecView Answer on Stackoverflow
Solution 2 - Pythonmike rodentView Answer on Stackoverflow
Solution 3 - PythoncahenView Answer on Stackoverflow
Solution 4 - PythonmdeView Answer on Stackoverflow
Solution 5 - PythonArtem KrylovView Answer on Stackoverflow