将Unix时间戳字符串转换为可读日期
我在Python中有一个字符串,表示一个Unix时间戳(比如“1284101485”),我想把它转换成一个容易阅读的日期。当我使用time.strftime
的时候,出现了一个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
20 个回答
197
最受欢迎的回答建议使用fromtimestamp这个方法,但这个方法容易出错,因为它会使用本地时区。为了避免这些问题,使用UTC(协调世界时)会是一个更好的选择:
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
这里的posix_time是你想要转换的Posix纪元时间。
329
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)
1575
使用 datetime
模块:
from datetime import datetime
ts = int('1284101485')
# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))