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

当前回答

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

其他回答

>>> 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'

使用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。(结果对象是朴素的。)

除了使用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'

对于来自UNIX时间戳的人类可读时间戳,我以前在脚本中使用过:

import os, datetime

datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

输出:

“2012年12月26日”

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

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

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