4

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
tattybojangler
  • 1,003
  • 3
  • 15
  • 25
  • https://stackoverflow.com/questions/7852855/how-to-convert-a-python-datetime-object-to-seconds – FCo Aug 31 '17 at 16:57

2 Answers2

7

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.

Divakar
  • 218,885
  • 19
  • 262
  • 358
2

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

Dharmesh Fumakiya
  • 2,276
  • 2
  • 11
  • 17