Unix timestamps are numerical representations of dates and times as seconds elapsed since the epoch (January 1, 1970, 00:00:00 UTC). While convenient for storage and manipulation, they are not human-readable. To convert a Unix timestamp string to a more presentable format, Python provides several useful modules.
The datetime module offers a comprehensive solution for timestamp conversion. The datetime.utcfromtimestamp() function takes a timestamp, expressed as an integer, and returns a datetime object representing the corresponding date and time in UTC. The strftime() method can then be used to format the datetime object according to a specified format string.
from datetime import datetime # Timestamp as a string timestamp = "1284101485" # Convert to datetime object dt = datetime.utcfromtimestamp(int(timestamp)) # Format using strftime formatted_date = dt.strftime("%Y-%m-%d %H:%M:%S") print(formatted_date)
This approach handles timestamps in both seconds and milliseconds, ensuring accurate conversion in various scenarios.
Alternatively, the time module provides the ctime() function to convert a timestamp to a human-readable string representation. While less versatile than the datetime module, ctime() can be utilized for basic timestamp conversion:
timestamp = "1284101485" # Convert to Unix timestamp unix_timestamp = int(timestamp) # Convert to human-readable string human_readable_date = time.ctime(unix_timestamp) print(human_readable_date)
The above is the detailed content of How Can I Convert Unix Timestamp Strings to Human-Readable Dates in Python?. For more information, please follow other related articles on the PHP Chinese website!