1

I have a numpy array which is built of decimal hours like so:

13.1 13.2 13.3 13.4
14.1 14.2 14.3 14.4
15.1 15.2 15.3 15.4

What I wish to do is convert this array to a time string and then replace all the values in this array with a custom string formatting. I calculate the times like so:

hours = int(time)
minutes = int((time*60) % 60)
seconds = int((time*3600) % 60)

From there the conversion will be done like so to get a time string:

ftime = "{}:{}:{}".format(str(hours), str(minutes), str(seconds))

And lastly I wish to use this formatting rule and replace all the values in the array with it so I get a result like so:

13:06:00 13:12:00 13:18:00 13:24:00
14:06:00 14:12:00 14:18:00 14:24:00
15:06:00 15:12:00 15:18:00 15:24:00

What is the best way to go about this?

2 Answers 2

1

You can simply multiply your array with a numpy.timedelta64() object representing 1 hour.

dates = np.array(hours * np.timedelta64(3600, 's'), dtype=str)

print(dates)
# [['13:06:00' '13:12:00' '13:18:00' '13:24:00']
#  ['14:06:00' '14:12:00' '14:18:00' '14:24:00']
#  ['15:06:00' '15:12:00' '15:18:00' '15:24:00']]
Sign up to request clarification or add additional context in comments.

1 Comment

This solution is equally valid as the first one however due to the fact that it is a single line solution makes it more preferable to me I'll be using this one so thank you for that.
1

You can use np.vectorize to make a function element wised.

import numpy as np

def format_time(time):
    hours = int(time)
    minutes = int((time*60) % 60)
    seconds = int((time*3600) % 60)
    return "{:02}:{:02}:{:02}".format(hours, minutes, seconds)

format_time = np.vectorize(format_time)

result = format_time(array)

1 Comment

Yep this is exactly what I was looking for thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.