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
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your answer! I also have another question that you may be able to help me with (I've edited my original post).
@tattybojangler Check out Edit section please.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.