tattybojangler
tattybojangler

Reputation: 1073

Storing datetime in numpy array

Let's say I want to store datetime values over 100 iterations of a for loop in a numpy array like so:

import numpy as np
import time 
from datetime import datetime

Startmult = np.zeros((1,100))
for i in range(100): 
    Startmult[i] = datetime.now()

Whenever I do this, I get the following error:

float() argument must be a string or a number, not 'datetime.datetime'

Is there a way to overcome this error?

Thank you for your help!

EDIT: Also, now I would like to do the following, but can't seem to find a solution:

 CPUtime = np.zeros((100), dtype='datetime64[s]')
 for i in range(100): 
     Start = datetime.now() 
     CPUtime[i] = datetime.now()-Start

In now get the following error:

Could not convert object to NumPy datetime

Upvotes: 4

Views: 12502

Answers (2)

Divakar
Divakar

Reputation: 221714

As pointed out in the error message, we need to use a compatible dtype there, float won't do. One of the compatible ones would be datetime64 and with it we need to specify the precision as well. Let's say we want for seconds. Then, the array initialization part would be -

Startmult = np.zeros((100), dtype='datetime64[s]')

All available time units are listed here.

Here's a sample run for nano-sec run on 100 elements case and verifying with the first and last output elements -

In [447]: Startmult = np.zeros((100), dtype='datetime64[ns]')
     ...: for i in range(100): 
     ...:     Startmult[i] = datetime.now()
     ...:     

In [448]: Startmult[0] # first element
Out[448]: numpy.datetime64('2017-08-31T22:39:45.722306000')

In [449]: Startmult[-1] # last element
Out[449]: numpy.datetime64('2017-08-31T22:39:45.723201000')

Edit : If you are trying to store the seconds elapsed between two points in time as floating pt numbers, you could do something like this -

CPUtime = np.zeros((100))
for i in range(100): 
    Start = datetime.now()
    time_diff = datetime.now()-Start
    CPUtime[i] = time_diff.total_seconds()

For u-sec precision, use : time_diff.microseconds.

Upvotes: 7

Dharmesh Fumakiya
Dharmesh Fumakiya

Reputation: 2338

your need to convert current datetime in integer format (only seconds)

Upvotes: 2

Related Questions