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

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

Barbara Streisand
Release: 2024-12-13 15:20:14
Original
197 people have browsed it

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

Converting Unix Timestamp Strings to Readable Dates in Python

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.

Using the datetime Module

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)
Copy after login

This approach handles timestamps in both seconds and milliseconds, ensuring accurate conversion in various scenarios.

Using the time Module

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template