将unix时间戳字符串转换为Python中的可读日期

将unix时间戳字符串转换为Python中的可读日期

问题描述:

我有一个表示Python中的unix时间戳(即1284101485)的字符串,我想将其转换为可读取的日期。当我使用 time.strftime 时,我得到一个 TypeError

I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a TypeError:

>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str


使用 datetime module:

import datetime
print(
    datetime.datetime.fromtimestamp(
        int("1284101485")
    ).strftime('%Y-%m-%d %H:%M:%S')
)

在此代码 datetime.datetime 可能看起来很奇怪,但第一个 datetime 是模块名,第二个是类名。所以 datetime.datetime.fromtimestamp() fromtimestamp()方法 datetime class from datetime module。

In this code datetime.datetime can look strange, but 1st datetime is module name and 2nd is class name. So datetime.datetime.fromtimestamp() is fromtimestamp() method of datetime class from datetime module.