Home >Backend Development >Python Tutorial >How to Convert Unix Timestamp Strings to Human-Readable Dates in Python?
Converting Unix Timestamp Strings to Readable Dates in Python
When working with Unix timestamps, it's often necessary to convert them into readable dates for human consumption. Python provides several methods for this purpose, one of which is time.strftime().
However, as mentioned in the given error message, using time.strftime() directly on a Unix timestamp string (which is a string representation of a number, e.g., "1284101485") can result in a TypeError.
To resolve this issue, we can use the datetime module instead. Here's how to convert a Unix timestamp string to a readable date using datetime:
from datetime import datetime ts = int('1284101485') # if you encounter a "year is out of range" error the timestamp # may be in milliseconds, try `ts /= 1000` in that case print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
This approach creates a datetime object from the Unix timestamp and then converts it to a human-readable format using the strftime() method. By default, it outputs the date and time in UTC (Coordinated Universal Time), but you can specify other timezones as needed.
The above is the detailed content of How to Convert Unix Timestamp Strings to Human-Readable Dates in Python?. For more information, please follow other related articles on the PHP Chinese website!