How to Convert Unix Timestamp to Milliseconds in Python?

Estimated read time 2 min read

To convert a Unix timestamp to milliseconds in Python, you can use the datetime module and the timestamp() method. Here’s an example:

import datetime

# Convert Unix timestamp to milliseconds
unix_timestamp = 1622046723  # Replace with your Unix timestamp
milliseconds = unix_timestamp * 1000

# Convert milliseconds to datetime object
dt = datetime.datetime.fromtimestamp(milliseconds / 1000.0)

# Print the milliseconds and the corresponding datetime object
print("Milliseconds:", milliseconds)
print("Datetime:", dt)

In this example, we have a Unix timestamp stored in the variable unix_timestamp. We multiply it by 1000 to convert it to milliseconds.

To convert the milliseconds back to a datetime object, we divide it by 1000.0 and use the datetime.datetime.fromtimestamp() method, passing the result as an argument. This method returns a datetime object representing the corresponding date and time.

Finally, we print the milliseconds and the corresponding datetime object for verification.

Note that the datetime module in Python uses the local time zone by default when converting the timestamp to a datetime object. If you want to work with UTC time, you can use the datetime.utcfromtimestamp() method instead:

dt = datetime.datetime.utcfromtimestamp(milliseconds / 1000.0)

This will return a datetime object representing the UTC time corresponding to the given milliseconds.

Make sure that the Unix timestamp you provide is in seconds. If the timestamp is in milliseconds or any other unit, you need to adjust the conversion accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply