Converting unix timestamp string to readable date

I have a string representing a unix timestamp (ie "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

Use datetime module:

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

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.


>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

取自http://seehuhn.de/pages/pdate


The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

Where posix_time is the Posix epoch time you want to convert

链接地址: http://www.djcxy.com/p/25196.html

上一篇: 使用JavaScript从元素中删除CSS类(无jQuery)

下一篇: 将unix时间戳字符串转换为可读的日期