SoFunction
Updated on 2024-11-15

Converting from 24-hour to 12-hour in python

12-24 hours

Write a program that asks the user to enter the time in 24-hour format and then displays the time in 12-hour format.

Input Format:
Input gives the time in 24-hour format with a center : sign (half colon) on one line, e.g., 12:34 means 12:34 minutes. When the number of hours or minutes is less than 10, there is no leading zero, e.g. 5:6 for 5:06.

Tip: Add : to scanf's format string to let scanf handle the colon.

Output format:
Outputs the 12-hour time corresponding to this time on a single line, with the numeric portion in the same format as typed, followed by a space, and then the string AM for morning or PM for afternoon, e.g., 5:6 PM for 5:06 PM. Note that in English conventions, 12:00 noon is considered to be the afternoon, so 12:00 in a 24-hour system is 12:0 PM in a 12-hour system; and 0:00 is considered to be the time of the next day, so it is 0:0 AM.

Input Sample:

21:11

Sample output:

9:11 PM

reasoning

The question can be analyzed by dividing the question into determining clocks less than 12, greater than 12 and equal to 12 to explore the results when converting from a 24-hour system to a 12-hour system.

take note of

This question should pay attention to the part of the 24-hour system that converts to a 12-hour system from 12:00 to 1:00, which needs to be judged separately.

coding

hour,minute = input().split(':')
hour = int(hour)
minute = int(minute)
if hour < 12:
    print('%d:%d AM'%(hour,minute))
elif hour == 12:
    print('%d:%d PM'%(hour,minute))
else:
    hour = hour-12
    print('%d:%d PM'%(hour,minute))

To this point, this article on the python 24-hour system converted to 12-hour system method of the article is introduced to this, more related python 24-hour system converted to 12-hour system content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!