Wednesday, November 7

Python program to print 12hr to 24hr format time.

def time24hr(tstr): 
new_time = tstr.split(":")
ampm = new_time[1]
ampm1 = ampm[2:]
hours = int(new_time[0])
if((ampm1 == "am") and (hours == 12)):
time1 = "00"+ampm[0:2]+"hr"
elif((ampm1 == "am") and (hours < 12)):
time1 = str("%02d" %hours)+ampm[0:2]+"hr"
elif((ampm1 == "pm") and (hours < 12)):
time1 = str(hours+12)+ampm[0:2]+"hr"
elif((ampm1 == "pm") and (hours == 12)):
time1 = str(hours)+ampm[0:2]+"hr"
print time1

Expected output

time24hr('12:34am')
>>> 0034hr
time24hr('7:34am')
>>> 0734hr
time24hr('7:34pm')
>>> 1934hr
time24hr('12:34pm')
>>> 1234hr



Be the first one to Comment!!!

Post a Comment