numpy has its own datetime and timedelta . Just use them;).
Settings, for example:
import datetime import numpy times = numpy.array([datetime.timedelta(0, 1, 36000)])
the code:
times.astype("timedelta64[ms]").astype(int) / 1000 #>>> array([ 1.036])
Since people do not seem to understand that this is the best solution, here are some timings of the timedelta64 array vs a datetime.datetime :
SETUP=" import datetime import numpy times = numpy.array([datetime.timedelta(0, 1, 36000)] * 100000) numpy_times = times.astype('timedelta64[ms]') " python -m timeit -s "$SETUP" "numpy_times.astype(int) / 1000" python -m timeit -s "$SETUP" "numpy.vectorize(lambda x: x.total_seconds())(times)" python -m timeit -s "$SETUP" "[delta.total_seconds() for delta in times]"
Results:
100 loops, best of 3: 4.54 msec per loop 10 loops, best of 3: 99.5 msec per loop 10 loops, best of 3: 67.1 msec per loop
The initial translation will take about twice as much time as the vectorized expression, but each operation from now on to infinity in this timedelta array will be about 20 times faster.
If you will never use these timedelta , think about why you ever made a delta (as opposed to timedelta64 s), and then used the expression numpy.vectorize . This is less native, but for some reason it is faster.
Veedrac
source share