我有一个字符串表示unix时间戳(即。"1284101485"),我想把它转换成一个可读的日期。当我利用时间的时候。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

当前回答

使用下面的代码,我希望它能解决你的问题。

import datetime as dt

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

其他回答

import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp

使用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'))

请注意,utcfromtimestamp可能会导致意想不到的结果,因为它返回一个朴素的datetime对象。Python将naive datetime视为本地时间——而UNIX时间指的是UTC。

可以通过在fromtimestamp中设置tz参数来避免这种歧义:

from datetime import datetime, timezone

dtobj = datetime.fromtimestamp(1284101485, timezone.utc)

>>> print(repr(dtobj))
datetime.datetime(2010, 9, 10, 6, 51, 25, tzinfo=datetime.timezone.utc)

现在你可以格式化为字符串,例如,符合ISO8601的格式:

>>> print(dtobj.isoformat(timespec='milliseconds').replace('+00:00', 'Z'))
2010-09-10T06:51:25.000Z

另一种方法是使用gmtime和format函数;

from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))

输出:2018-10-4 11:57:44

投票最多的答案是使用fromtimestamp,这很容易出错,因为它使用本地时区。为了避免问题,一个更好的方法是使用UTC:

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

posix_time是要转换的Posix纪元时间