Convert numpy array of seconds to minutes and seconds

2.2k views Asked by At

Here is a good stack overflow question on how to go from seconds to hours, minutes and seconds: How do I convert seconds to hours, minutes and seconds?

However, I couldn't find how to convert a numpy array of seconds to minutes:seconds. I have a plot with it's ticks being seconds, so I want to convert that min and sec.

Data

# example data
tick_sec = np.array([-5., 0., 5., 10., 15., 20., 25., 30., 35., 40., 55., 60., 65., 70.])
# origin of data: tick_sec = ax.get_xticks()

timedelta attempt

import datetime

datetime.timedelta(seconds=tick_sec)

Gives:

TypeError                                 Traceback (most recent call last)
<ipython-input-29-cc4fdae20757> in <module>
      1 import datetime
      2 
----> 3 datetime.timedelta(seconds=tick_sec)

TypeError: unsupported type for timedelta seconds component: numpy.ndarray

divmod attempt (working)

def sec_to_minsec(sec_arr):
    tick_min, tick_sec = divmod(sec_arr, 60)  # returns 2 numpy.ndarray
    print(type(tick_min))

    tick_m_s = np.empty([tick_min.size], dtype=(np.str, 8))  # init empty string array
    for i, min_sec in enumerate(zip(tick_min, tick_sec)):  # loop over 2 arrays
        tick_m_s[i] = f"{int(min_sec[0]):02d}:{int(min_sec[1]):02d}"  # add 0 before min and sec

    return tick_m_s

sec_to_minsec(tick_sec)

Output:

array(['-1:55', '00:00', '00:05', '00:10', '00:15', '00:20', '00:25',
       '00:30', '00:35', '00:40', '00:55', '01:00', '01:05', '01:10'],
      dtype='<U8')

Works, but I feel this could be more efficient? Also, it gives a weird output for negative time (although that's not of concern for my current problem)

System

  • Python 3.6 in a Jupyter Notebook environment

Question

Is there a better/efficient/shorter code way to do my divmod attempt?

1

There are 1 answers

0
benvc On

Not sure if it is more efficient or not, but you can get it done with timedelta. Performance is highly dependent on the complete dataset among other things, so you should run some tests to determine what is really best in your situation.

For example:

from datetime import timedelta
import numpy as np

tick_sec = np.array([-5., 0., 5., 10., 15., 20., 25., 30., 35., 40., 55., 60., 65., 70.])

tick_hms = np.array([str(timedelta(seconds=s)) for s in tick_sec])
print(tick_hms)
# ['-1 day, 23:59:55' '0:00:00' '0:00:05' '0:00:10' '0:00:15' '0:00:20' '0:00:25' '0:00:30' '0:00:35' '0:00:40' '0:00:55' '0:01:00' '0:01:05' '0:01:10']