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

当前回答

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

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

posix_time是要转换的Posix纪元时间

其他回答

你可以像这样转换当前时间

t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'

将字符串中的日期转换为不同的格式。

import datetime,time

def createDateObject(str_date,strFormat="%Y-%m-%d"):    
    timeStamp = time.mktime(time.strptime(str_date,strFormat))
    return datetime.datetime.fromtimestamp(timeStamp)

def FormatDate(objectDate,strFormat="%Y-%m-%d"):
    return objectDate.strftime(strFormat)

Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')

Output 03-03-2013
timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')

从带有时间的时间戳中获取可读的日期,还可以更改日期的格式。

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

import os, datetime

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

输出:

“2012年12月26日”

我刚刚成功地使用了:

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

如果你正在使用一个数据帧,并且不希望系列不能转换为类int错误。使用下面的代码。

new_df= pd.to_datetime(df_new['time'], unit='s')