How to convert unix timestamp string to readable date in Python?

You can use the fromtimestamp() function from the datetime module to convert a UNIX timestamp string to a readable date format. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp.

Converting Unix Timestamp to Readable Date

Here's how to convert a Unix timestamp string to a readable date format ?

import datetime

# Convert timestamp string to readable date
timestamp_str = "1500000000"
timestamp = datetime.datetime.fromtimestamp(int(timestamp_str))
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

The output of the above code is ?

2017-07-14 08:10:00

Using Different Date Formats

You can customize the output format using different strftime codes ?

import datetime

timestamp_str = "1500000000"
timestamp = datetime.datetime.fromtimestamp(int(timestamp_str))

# Different format options
print("Full date:", timestamp.strftime('%A, %B %d, %Y'))
print("Time only:", timestamp.strftime('%H:%M:%S'))
print("ISO format:", timestamp.strftime('%Y-%m-%dT%H:%M:%S'))
Full date: Friday, July 14, 2017
Time only: 08:10:00
ISO format: 2017-07-14T08:10:00

Handling Different Time Zones

To handle different time zones, you can use the pytz library ?

import datetime
import pytz

timestamp_str = "1500000000"

# Convert to UTC
utc_time = datetime.datetime.utcfromtimestamp(int(timestamp_str))
print("UTC time:", utc_time.strftime('%Y-%m-%d %H:%M:%S'))

# Convert to specific timezone
utc_time = utc_time.replace(tzinfo=pytz.UTC)
eastern = utc_time.astimezone(pytz.timezone('US/Eastern'))
print("Eastern time:", eastern.strftime('%Y-%m-%d %H:%M:%S %Z'))
UTC time: 2017-07-14 02:40:00
Eastern time: 2017-07-13 22:40:00 EDT

Conclusion

Use datetime.fromtimestamp() to convert Unix timestamps to readable dates. Remember to convert string timestamps to integers first, and consider timezone handling for accurate time representation.

Updated on: 2026-03-24T19:22:00+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements