Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a datetime in Python from milliseconds?

People also ask

How do you convert milliseconds to dates?

Approach : First declare variable time and store the milliseconds of current date using new date() for current date and getTime() Method for return it in milliseconds since 1 January 1970. Convert time into date object and store it into new variable date. Convert the date object's contents into a string using date.

How do you represent milliseconds in a date format in Python?

strptime() function in python converts the string into DateTime objects. The strptime() is a class method that takes two arguments : string that should be converted to datetime object.

Is Python time time in milliseconds?

You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time. time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off.


Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)

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)

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')

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