0

I need to make a simple program which converts a 24 hour time which is input, into 12 hour time, which produces an error if an incorrect time is put in. I currently have the code below, however, I have a few issues. One issue is that if "0924" is input, it outputs "924 am", when I need it to produce "9:24am" (the space isn't hugely important but it's preferred). Also, I'm not entirely sure where to start for doing 0001-0059, because "0001" for example produces "1 am", which is obviously incorrect.

print("Enter a time in 24 hour time, e.g. '1620'")

time = (int(input("Time: ")))

normal = 0

if (time == 0000):

    normal="12:00am"
    print (normal)

elif (time>1200):

    normal = (time - 1200)
    print (int(normal), ("pm"))

elif (time<1200):

    normal = time
    print (int(normal), ("am"))

Thanks in advance for any help!

theBrainyGeek
  • 584
  • 1
  • 6
  • 17
mememan9001
  • 31
  • 1
  • 8

3 Answers3

1

When printing, normal is just a number. The 0s disappear because you don't write 0s in front of numbers normally. I would suggest doing something like this

def normal_check(num):
    if num < 10:
        return "000"+str(num)
    elif num < 100:
        return "00"+str(num)
    elif num < 1000:
        return "0"+str(num)
    else:
        return str(num)

print("Enter a time in 24 hour time, e.g. '1620'")

time = (int(input("Time: ")))

normal = 0

if (time == 0000):

    normal="12:00am"
    print (normal)

elif (time>1200):

    normal = normal_check(time - 1200)
    print (normal, ("pm"))

elif (time<1200):

    normal = normal_check(time)
    print (normal, ("am"))
Yardid
  • 247
  • 1
  • 6
1

Try this

import time
timevalue_24hour = "1620";
timevalue_24hour = timevalue_24hour[:2] + ':' + timevalue_24hour[2:]
print (timevalue_24hour)
t = time.strptime(timevalue_24hour, "%H:%M")
timevalue_12hour = time.strftime( "%I:%M %p", t )
print (timevalue_12hour) 

Take input as a string. Assign it to timevalue_24hour and rest will work

Muhammad Usman
  • 10,039
  • 22
  • 39
-1

The best way to do this will be to take the input as an str rather than int. Take it in as str and split it into two int values of two digits. Then the first string if less than 12 will be hour else subtract 12 from first str and use PM. Also, the second str will just be minutes.

theBrainyGeek
  • 584
  • 1
  • 6
  • 17