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. Here is an example:
import datetime
# UNIX timestamp string
timestamp = "1588291200"
# Convert timestamp to datetime object
readable_date = datetime.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.
Watch a video course
Python - The Practical Guide
Note that the returned datetime object is in the local timezone, if you want to change it to a specific timezone you can use the pytz
library.
from datetime import datetime
import pytz
unix_ts = 1588291200
#convert unix timestamp to datetime
dt_object = datetime.fromtimestamp(unix_ts)
#set timezone to UTC
tz = pytz.timezone('UTC')
dt_object = dt_object.replace(tzinfo=tz)
print(dt_object)
In this example the datetime object will be in UTC timezone.