179k views
1 vote
Write a program that converts a time in 12-hour format to 24-hour format. The program will prompt the user to enter a time in HH:MM:SS AM/PM form. (The time must be entered exactly in this format all on one line.) It will then convert the time to 24 hour form. You may use a string type to read in the entire time at once, including the space before AM/PM, or you may choose to use separate variables for the hours, minutes, seconds and AM/PM.

User Warner
by
5.0k points

1 Answer

5 votes

Answer:

This program is written in Python

inputtime = input("HH:MM:SS AM/PM: ")

splittime = inputtime.split(":")

secondAM = splittime[2].split()

if secondAM[1] == "AM":

print(splittime[0]+":"+splittime[1]+":"+secondAM[0])

elif secondAM[1] == "PM":

HH = int(splittime[0])

HH = HH + 12

print(str(HH)+":"+splittime[1]+":"+secondAM[0])

Step-by-step explanation:

This line prompts user for input

inputtime = input("HH:MM:SS AM/PM: ")

This line splits the input string to HH, MM and "SS AM/PM"

splittime = inputtime.split(":")

This line splits "SS AM/PM" to SS and AM/PM

secondAM = splittime[2].split()

This line checks if time is AM

if secondAM[1] == "AM":

This line prints the equivalent time

print(splittime[0]+":"+splittime[1]+":"+secondAM[0])

Else;

elif secondAM[1] == "PM":

The equivalent 24 hour is calculated

HH = int(splittime[0]) + 12

This line prints the equivalent time

print(str(HH)+":"+splittime[1]+":"+secondAM[0])

User Mohammad Adnan
by
4.3k points