How to Convert Unix Timestamp to Datetime in Python?

Estimated read time 2 min read

To convert a Unix timestamp to a datetime object in Python, you can use the datetime module. Here’s an example:

import datetime

# Convert Unix timestamp to datetime object
unix_timestamp = 1622046723  # Replace with your Unix timestamp
dt = datetime.datetime.fromtimestamp(unix_timestamp)

# Print the Unix timestamp and the corresponding datetime object
print("Unix Timestamp:", unix_timestamp)
print("Datetime:", dt)

In this example, we have a Unix timestamp stored in the variable unix_timestamp. We use the datetime.datetime.fromtimestamp() method, passing the Unix timestamp as an argument. This method returns a datetime object representing the corresponding date and time.

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

Note that the datetime object represents the local time based on the system’s time zone. If you want to work with UTC time, you can use the datetime.utcfromtimestamp() method instead:

dt = datetime.datetime.utcfromtimestamp(unix_timestamp)

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

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.

Additionally, keep in mind that Unix timestamps are typically stored as a number of seconds since January 1, 1970, at 00:00:00 UTC. However, some systems or APIs may use a different epoch or a different unit (e.g., milliseconds). In such cases, you need to adjust the conversion accordingly to match the specific epoch or unit being used.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply