Easily Convert Unix Timestamp Strings to Readable Dates
When working with time stamps, it becomes necessary to convert raw timestamp strings into more readable formats. In Python, you may encounter a TypeError when using time.strftime to format a Unix timestamp string. To resolve this issue and successfully convert these strings into human-readable dates, consider the following:
Using the datetime Module:
The datetime module provides a more straightforward approach to handling date and time operations in Python. Here's how you can use it:
from datetime import datetime ts = int('1284101485') # Check if the timestamp requires conversion from milliseconds if ts > 1e9: ts /= 1000 print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
This method uses datetime.datetime to convert the Unix timestamp string into a datetime object. The utcfromtimestamp() method creates a datetime object from a Unix timestamp in UTC (Coordinated Universal Time). Finally, the strftime() method is used to format the datetime object into a readable string using the specified format (%Y-%m-%d %H:%M:%S).
Remember, if you encounter a "year is out of range" error, the timestamp string may be in milliseconds. To resolve this, divide the timestamp value by 1000 before converting it to a datetime object.
The above is the detailed content of How to Easily Convert Unix Timestamp Strings to Human-Readable Dates in Python?. For more information, please follow other related articles on the PHP Chinese website!