Just convert it to timestamp
datetime.datetime.fromtimestamp(ms/1000.0)
Answer from vartec on Stack OverflowConvert python datetime to timestamp in milliseconds - Stack Overflow
python - Format a datetime into a string with milliseconds - Stack Overflow
Converting unix timestamps in python
How to convert a number of milliseconds since Year 0 into a pandas Timestamp (or some other object with year, month, day, hour, minute, second)?
Videos
In Python 3 this can be done in 2 steps:
- Convert timestring to
datetimeobject - Multiply the timestamp of the
datetimeobject by 1000 to convert it to milliseconds.
For example like this:
from datetime import datetime
dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output:
1482223122760.0
strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.
Here is the explanation of the format specifiers from the official documentation:
%d- Day of the month as a zero-padded decimal number.%m- Month as a zero-padded decimal number.%Y- Year with century as a decimal number%H- Hour (24-hour clock) as a zero-padded decimal number.%M- Minute as a zero-padded decimal number.%S- Second as a zero-padded decimal number.%f- Microsecond as a decimal number, zero-padded to 6 digits.
For those who search for an answer without parsing and losing milliseconds,
given dt_obj is a datetime:
python3 only, elegant
int(dt_obj.timestamp() * 1000)
both python2 and python3 compatible:
import time
int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)
To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'
Or shorter:
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]
'2022-09-24 10:18:32.926'
See the Python docs for more "%" format codes and the strftime(3) man page for the full list.
With Python 3.6+, you can set isoformat's timespec:
>>> from datetime import datetime
>>> datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
'2019-05-10 09:08:53.155'
Hi I'm trying to figure out how to convert unix timestamps. My code just looks like this right now but I'm getting the following error. Anybody know what I'm doing wrong?
import datetime timestamp = 1729322547223 dt_object = datetime.datetime.fromtimestamp(timestamp) print(dt_object) Traceback (most recent call last): File "c:\Users\elieh\OneDrive\Documents\friendsgg\main.py", line 21, in <module> dt_object = datetime.datetime.fromtimestamp(timestamp) OSError: [Errno 22] Invalid argument