Skip to content
Advertisement

How do I convert an array of seconds to time series array in Python?

I have an array like this (in seconds) timebin= [79203 79213 79223 79233 79243 79253 79263..................82783] and I wish to convert these values to actual time of the day like [22:00:03, 22:00:13,.........22:59:43] I have the following code but it doesn’t convert an entire array to time array in one go and only takes single values of timebin.

timebin1=np.arange(79203,82793,10)
print(timebin)
import time
t= time.strftime('%H:%M:%S', time.gmtime(79203))
print(t)

output for now is only the first value of the required time series, i.e, 22:00:03

Advertisement

Answer

You’ll want to apply that function to each element in the list.

convert_time = lambda t: time.strftime('%H:%M:%S', time.gmtime(t))

times = [convert_time(t) for t in timebin1]

For slightly faster results and a more convenient API, you can vectorize the operation:

import numpy as np

vectorized_convert_time = np.vectorize(convert_time)
times = vectorized_convert_time(timebin1)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement