W3docs

Converting unix timestamp string to readable date

You can use the datetime module in Python to convert a UNIX timestamp string to a readable date.

You can use the datetime module in Python to convert a UNIX timestamp string to a readable date. Here is an example:

Convert a UNIX timestamp string to a readable date in Python

from datetime import datetime

# UNIX timestamp string
timestamp = "1588291200"

# Convert timestamp to datetime object
readable_date = datetime.fromtimestamp(int(timestamp))

print(readable_date)

The fromtimestamp() method takes a UNIX timestamp as an argument and returns a datetime object. The int() function is used to convert the timestamp string to an integer.

Note that the returned datetime object defaults to the system local timezone. UNIX timestamps are inherently in UTC. To explicitly handle UTC or convert to another timezone, use the built-in zoneinfo module (Python 3.9+):

Convert a UNIX timestamp string to a readable date in Python and convert the timezone

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

unix_ts = 1588291200

# Convert timestamp to datetime object
dt_object = datetime.fromtimestamp(unix_ts)

# Convert to UTC
dt_utc = dt_object.astimezone(timezone.utc)

# Convert to a specific timezone (e.g., US/Eastern)
dt_ny = dt_object.astimezone(ZoneInfo("US/Eastern"))

print(dt_utc)
print(dt_ny)

In this example, the datetime object is explicitly converted to UTC or a specific timezone using astimezone(), which safely handles DST transitions.