[英]AttributeError: 'str' object has no attribute 'strftime' in python
[英]“AttributeError: 'matrix' object has no attribute 'strftime'” error in numpy python
我有一个尺寸为(72000,1)的矩阵。 该矩阵涉及时间戳。
我想使用“ strftime”如下: strftime("%d/%m/%y")
,以获取如下输出: '11/03/02'
。
我有这样一个矩阵:
M = np.matrix([timestamps])
为了将所有包含时间戳的矩阵转换为包含字符串类型中的日期的矩阵,我使用了“ strftime”。 出于这个原因,我将“ strftime”用作了以下用法:
M = M.strftime("%d/%m/%y")
运行代码时,出现以下错误:
AttributeError: 'matrix' object has no attribute 'strftime'
使用此功能的正确方法是什么? 如何将时间戳矩阵转换为日期字符串矩阵?
如错误消息所示,您不能执行诸如matrix.strftime
类的matrix.strftime
。 您可以做的一件事是使用numpy.apply_along_axis
。 范例-
np.apply_along_axis((lambda x:[x[0].strftime("%d/%m/%y")]),1,M)
演示-
In [58]: M = np.matrix([[datetime.datetime.now()]*5]).T
In [59]: M.shape
Out[59]: (5, 1)
In [60]: np.apply_along_axis((lambda x:[x[0].strftime("%d/%m/%y")]),1,M)
Out[60]:
array([['10/10/15'],
['10/10/15'],
['10/10/15'],
['10/10/15'],
['10/10/15']],
dtype='<U8')
对于新错误,您得到-
“ AttributeError:'numpy.float64'对象没有属性'strftime'”
这意味着这些对象不是datetime
对象,因此,如果它们是时间戳记,则可以先将它们转换为日期时间。 范例-
np.apply_along_axis((lambda x:[datetime.datetime.fromtimestamp(x[0]).strftime("%d/%m/%y")]),1,M)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.