Home > database >  How to convert datetime.datetime to array?
How to convert datetime.datetime to array?

Time:11-23

I have an array that contains datetime.datetime objects. They are as follows:

array([datetime.datetime(2011, 1, 1, 0, 3, 32, 262000),
       datetime.datetime(2011, 1, 1, 0, 5, 7, 290000),
       datetime.datetime(2011, 1, 1, 0, 6, 45, 383000),
       datetime.datetime(2011, 1, 1, 0, 8, 23, 335000)], dtype=object)

I am trying to save this data as a .mat file using savemat through this command.

save_structure = {'Time':time_array}
savemat(path   '\2011.mat',save_structure)

Here .mat is the matlab format file.

I have used the following libraries:

from spacepy import pycdf
from scipy.io import savemat,loadmat
import datetime

It gives me the following error:

TypeError: Could not convert 2011-01-01 00:03:32.262000 (type <class 'datetime.datetime'>) to array

One of the ways through which I was getting through was by converting the following data into Unix but now I need these particular data for ease in my further data analysis. Is there a way to achieve what I am trying to?

CodePudding user response:

Convert the datetime.datetime to numpy.datetime64 first, then scipy seems to know how to handle the conversion:

import datetime

import numpy as np
from scipy.io import savemat

time_array = np.array([datetime.datetime(2011, 1, 1, 0, 3, 32, 262000),
       datetime.datetime(2011, 1, 1, 0, 5, 7, 290000),
       datetime.datetime(2011, 1, 1, 0, 6, 45, 383000),
       datetime.datetime(2011, 1, 1, 0, 8, 23, 335000)])

time_array_np = time_array.astype(np.datetime64)
save_structure = {'Time': time_array_np}
savemat('2011.mat', save_structure)
  • Related