Search code examples
pythonnumpymatrixstrftime

"AttributeError: 'matrix' object has no attribute 'strftime'" error in numpy python


I have a matrix with (72000, 1) dimension. This matrix involves timestamps.

I want to use "strftime" as the following; strftime("%d/%m/%y"), in order to get the output something like this: '11/03/02'.

I have such a matrix:

M = np.matrix([timestamps])

And I have used "strftime" in order to convert all the matrix involving timestamps to a matrix involving dates in string types. For this reason, I have used "strftime" as the follwing:

M = M.strftime("%d/%m/%y")

When I run the code, I get this error:

AttributeError: 'matrix' object has no attribute 'strftime'

What is the right way of using this function? How can I convert the timestamp matrix to date string matrix?


Solution

  • As the error message shows you, you cannot do something like matrix.strftime . One thing you can do would be to use numpy.apply_along_axis . Example -

    np.apply_along_axis((lambda x:[x[0].strftime("%d/%m/%y")]),1,M)
    

    Demo -

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

    For the new error you are getting -

    "AttributeError: 'numpy.float64' object has no attribute 'strftime'"

    This means that the objects are not datetime objects, so if they are timestamps , you can converting them to datetime first. Example -

    np.apply_along_axis((lambda x:[datetime.datetime.fromtimestamp(x[0]).strftime("%d/%m/%y")]),1,M)