Skip to content
Advertisement

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

Advertisement

Answer

import numpy as np

helper = np.vectorize(lambda x: x.total_seconds())
dt_sec = helper(dt)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement