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

当前回答

在Python 3.6+中:

import datetime

timestamp = 1642445213
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")

输出(本地时间)

2022-01-17 20:46:53

解释

第1行:导入datetime库。 第2行:Unix时间,从1970-01-01开始,单位是秒。 第3行:将其转换为unix时间对象,检查:type(value) 第4行:打印与strp相同的格式。当地时间。要以UTC打印,请参阅下面的示例。

奖金

要将日期保存为字符串,然后打印它,使用以下命令:

my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)

以UTC格式输出:

value = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
# 2022-01-17 18:50:52

其他回答

import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

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

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

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

posix_time是要转换的Posix纪元时间

使用datetime.strftime(格式):

from datetime import datetime
unixtime = int('1284101485')

# Print with local time
print(datetime.fromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))

# Print with UTC time
print(datetime.utcfromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))

datetime.fromtimestamp(timestamp):返回与POSIX时间戳对应的本地日期,例如time.time()返回的日期。 datetime.utcfromtimestamp(timestamp):返回与POSIX时间戳对应的UTC日期时间,tzinfo为None。(结果对象是朴素的。)

我刚刚成功地使用了:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date