Converting a 2d vector to hours

Viewed 104

I have a two dimensional vector hour_vector that represents the small hand of a clock, and I want to convert this vector to show the hour it indicates.

For example, the vector [0, 1] represents "12:00" on the clock, or the vector [1, 0] represents "3:00". Similarly, the vector [1, 1] shows "1:30" and so does [2,2] and [10,10] i.e. vectors of different lengths which are pointing to the same direction represent the same time.

I started by calculating the angle between two vectors (one being the origin) but I'm unsure where to progress from here:

import numpy as np

def angle(a, b):
    dot_product = round(np.dot(a, b), 1)
    angle = round(np.degrees(np.arccos(dot_product / (np.linalg.norm(a) * np.linalg.norm(b)))), 1)
    return angle

print(angle_dot(np.array([0., 1.]), np.array([1., 0.])))
## 90.0
1 Answers

With the angle calculated, you just need to map those angles to the range of hours, which is quite simple since they both start at 0. Try:

ang = angle(a, b) # Get angle of the vector between 0..360

hour = ang / 360.0 * 12.0 # Scales to hour as float (i.e. 90.0 -> 3.0)

hour_str = f'{int(hour):02}:{int((hour * 60) % 60):02}'

For the angle of 45 degrees, these values are:

ang = 45.0
hour = 1.5
hour_str = '01:30'
Related