Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elegant way of convert a numpy array containing datetime.timedelta into seconds in python 2.7

I have a numpy array called dt. Each element is of type datetime.timedelta. For example:

>>>dt[0]
datetime.timedelta(0, 1, 36000)

how can I convert dt into the array dt_sec which contains only seconds without looping? my current solution (which works, but I don't like it) is:

dt_sec = zeros((len(dt),1))
for i in range(0,len(dt),1):
    dt_sec[i] = dt[i].total_seconds()

I tried to use dt.total_seconds() but of course it didn't work. any idea on how to avoid this loop?

Thanks

like image 258
otmezger Avatar asked Sep 26 '13 21:09

otmezger


1 Answers

import numpy as np

helper = np.vectorize(lambda x: x.total_seconds())
dt_sec = helper(dt)
like image 174
prgao Avatar answered Sep 28 '22 12:09

prgao