Home >Backend Development >Python Tutorial >How to Easily Convert Unix Timestamp Strings to Human-Readable Dates in Python?

How to Easily Convert Unix Timestamp Strings to Human-Readable Dates in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 20:52:19394browse

How to Easily Convert Unix Timestamp Strings to Human-Readable Dates in Python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn