In this blog, you will learn how to calculate the angle between the hour and minute hands of a clock using Python. The solution is based on a simple mathematical approach explained below.
At 12:00, both the hour and minute hands align at the 12 o’clock position. To calculate the angle at any given time:
- Calculate the “hour hand angle” and the “minute hand angle” relative to the 12 o’clock position.
- Take their absolute difference to determine the angle between the two hands.
- If you need the minimum angle, compare the absolute difference with 360°- absolute difference and take the smaller value.
Here are the key formulas:
Hour Hand Angle: The hour hand moves 30° per hour and 0.5° per minute. Therefore,
Hour Hand Angle = (H*30) + (M*0.5), where H is the hour, and M is the minutes past the hour.
Minute Hand Angle: The minute hand moves 6° per minute. Therefore, Minute Hand Angle = M*6
The angle between the hands is:
Absolute Angle = ∣Hour Hand Angle – Minute Hand Angle∣
To run the following Python code, provide the time as a command-line argument in the following format:
python calc_angle.py 8:15
Here, calc_angle.py is the name of the program containing the code. If you use a different filename, replace calc_angle.py with your program’s name. 8:15 represents the time for which you want to calculate the angle between the hour and minute hands.
import sys
def validate_time(user_time):
"""
check if user provided correct time
"""
hrs, mins = int(user_time.split(':')[0]), int(user_time.split(':')[1])
if 0 <= hrs <= 12 and 0 <= mins <= 59:
return True, hrs, mins
else:
return False, hrs, mins
def calculate_angle(hour, minute):
"""
Find angle between hour and minute hands
"""
# Calculate the position of the hour hand in degrees w.r.t 12
hour_angle = (hour * 30) + (minute * 0.5)
# Calculate the position of the minute hand in degrees w.r.t 12
minute_angle = minute * 6
# Calculate the absolute difference between the two angles
angle = abs(hour_angle - minute_angle)
# The smaller angle between the two hands
return min(angle, 360 - angle)
def main():
"""
This program calculates the angle between minute and hour hands for a given time
"""
# provide time as command-line argument, e.g. 10:45
args = sys.argv
# check if user provided time or not
if len(args) < 2:
print("No time provided. please enter time (e.g. 9:45) as command-line argument")
else:
# print("time provided by user: ", args[1])
# validate time provided by user
correct_time, hh, mm = validate_time(args[1])
if correct_time:
angle = calculate_angle(hh, mm)
print(f"the angle between the hour and minute hands at {args[1]} is {angle} degrees.")
else:
print(f"{args[1]} is invalid time")
if __name__ == "__main__":
main()
Please let me know in the comments if you find any errors in the code.