Convert Timestamp to Milliseconds since Epoch in Python

Kontext Kontext event 2022-08-22 visibility 5,027
more_vert

Code description

This code snippets provides different approaches to convert a Python timestamp object to an integer that denotes the total milliseconds since Epoch (midnight 1st Jan 1970 UTC, UNIX time).

Output:

1661169251815.902
1661133251815.902

*Your result can be different depends on the time when you run the code. The result is the same no matter if we use utcnow() or now() as they both represent the same time.

However, if your input timestamp format is string, you need to be careful about time zone information when converting them to timestamp, i.e. specify the right time zone accordingly. 

Code snippet

import datetime

now = datetime.datetime.utcnow()
now_local = datetime.datetime.now()

epoch = datetime.datetime.utcfromtimestamp(0)

milliseconds = (now - epoch).total_seconds() * 1000.0
print(milliseconds)

# For python version >=3.3
milliseconds = now.timestamp()*1000.0
print(milliseconds)
More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts