How do I create a datetime in Python from milliseconds?

Viewed 210038

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.

5 Answers

Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)

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

Bit heavy because of using pandas but works:

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

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