我有一个字符串表示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

当前回答

你可以使用easy_date来简化:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")

其他回答

又快又脏的一句话:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

'the 2013-5-5-2013-5-5'

除了使用time/datetime包,还可以使用pandas来解决相同的问题。下面是如何使用pandas将时间戳转换为可读日期:

时间戳可以有两种格式:

13位(毫秒)- 要将毫秒转换为日期,请使用: 进口熊猫 result_ms = pandas.to_datetime(' 1493530261000 ',单位=“女士”) str (result_ms) 输出:'2017-04-30 05:31:01' 10位数(秒)- 要将秒转换为日期,请使用: 进口熊猫 result_s = pandas.to_datetime(' 1493530261 ',单位= ' s ') str (result_s) 输出:'2017-04-30 05:31:01'

你可以使用easy_date来简化:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")

请注意,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
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'