How to convert an array of seconds into dd:hh:mm:ss in Python?

Question:

I have a numpy array that is created using the code below after it has been read from a .nc file generated from https://map.neweuropeanwindatlas.eu/

timeSec = numpy.arange(0, len(time)*(time[2] - time[1])*60,  (time[2] - time[1])*60, dtype=int)

I then found a way to convert this array into a format "#day, hh:mm:ss" (for e.g. "1 day, 12:30:00") using

timeSec = numpy.array([str(timedelta(seconds=int(s))) for s in timeSec])

However, I would like to have it in the format dd:hh:mm:ss. Because I have to create a .csv file that will be read into another simulation software that requires it in this particular format. Is there another way change the seconds into the format I require? I suspect that there might be a way carrying mathematical operations and then displaying it in correct format but I am not savy enough in coding to come up with a solution on my own. Any help or advice will be highly appreciated. Thank you in advance.

Asked By: Jalal Kehar

||

Answers:

For example:

def secToFormat(sec):
    sec = int(sec)
    # Calculate days by using floor division
    dd = sec // 86400
    # Subtract days as seconds, then takes floor divison from leftover as hours
    hh = (sec - dd * 86400) // 3600
    # Subtract days and hours as seconds, then takes floor divison from leftover as minutes
    mm = (sec - dd * 86400 - hh * 3600) // 60
    # Subtract days, hours and minutes as seconds, then use leftover as seconds
    ss = sec - dd * 86400 - hh * 3600 - mm * 60
    # Formatting output as dd:hh:mm:ss
    return f"{dd:02d}:{hh:02d}:{mm:02d}:{ss:02d}"


# Looping through timeSec array and sending them through the function
timeSec = numpy.array([secToFormat(s) for s in timeSec])
Answered By: valtteri k
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.