# 12 hour to 24 hour time conversion

doing hackerrank challenges and been learning python3 for a month now, made this code to convert and return 12 hour to 24 hour time format in one of the challenges

s ="05:43:12PM"
#s normally is input, but this code will only work with this type of string input

def timeconversion(s):
l = list(s.strip(':'))
print(l)

hour = l[0] + l[1]
minutes = l[3]+ l[4]
seconds = l[6] + l[7]
print(hour)
print(minutes)
print(seconds)
zone = l[8] + l[9]
if zone == 'PM' and hour != '12':
time = int(hour) + 12

print(f"{time}:{minutes}:{seconds}")
elif zone == 'PM' and hour == '12':
print(f"{hour}:{minutes}:{seconds}")

elif zone == 'AM' and hour == '12':
print(f"00:{minutes}:{seconds}")
elif zone == 'AM':
print(f"{hour}:{minutes}:{seconds}")

timeconversion(s)


recommended learning materials and similar i can learn from,

busy studing from a book called learn python3 the hard way by Zed Shaw about a third of the way through it.

• Is there a reason you aren't using built-in datetime processing? Jun 16 at 17:11

## Program structure

timeconversion is not a very descriptive function name. What is it converting from, and what is it converting to? I suggest convert_12h_to_24h as a function name. It would be better for the function to return its result rather than printing it, so that the caller of the function can decide what to do with the result.

A function should have a docstring, especially a function like this that expects its input to be in a very specific format.

You should put the function definition first. Plopping a function definition into the middle of the "main" program makes your code harder to understand.

So far, we would have…

def convert_12h_to_24h(s):
"""
Convert a time from a 12-hour format into 24-hour format.

The input should be a 10-character string like "01:23:45PM", and the
output would be "13:23:45".
"""
…
return …

s = "05:43:12AM"
print(convert_12h_to_24h(s))


## Variables

zone is a poor choice of variable name, because it makes me think of timezones. I don't know exactly what the right terminology is for a half-day, but I'd choose am_pm for the variable name.

Likewise, time is a poor variable name. You could just call it hour again.

It's a bit weird that hour is singular, but minutes and seconds are plural.

l = list(s.strip(':')) is pointless — you could just use s directly.

The multiple variable assignment statements for extracting parts of the string could be written more elegantly using string slices and multiple assignment:

hours, minutes, seconds, am_pm = s[0:2], s[3:5], s[6:8], s[8:10]


I'd recommend dissecting the string using indexing from the end, so that it works whether or not there is a leading 0:

hours, minutes, seconds, am_pm = s[-10:-8], s[-7:-5], s[-4:-2], s[-2:]


## Putting it all together

One additional change I'd make is to swap the first two branches if your if-elif chain for consistency.

def convert_12h_to_24h(s):
"""
Convert a time from a 12-hour format into 24-hour format.

The input should be a 10-character string like "01:23:45PM", and the
output would be "13:23:45".
"""
hours, minutes, seconds, am_pm = s[-10:-8], s[-7:-5], s[-4:-2], s[-2:]
if am_pm == 'PM' and hours == '12':
return f"{hours}:{minutes}:{seconds}"
elif am_pm == 'PM':
hours = int(hours) + 12
return f"{hours}:{minutes}:{seconds}"
elif am_pm == 'AM' and hours == '12':
return f"00:{minutes}:{seconds}"
elif am_pm == 'AM':
return f"{hours}:{minutes}:{seconds}"

#s normally is input, but this code will only work with this type of string input
s = "05:43:12AM"
print(convert_12h_to_24h(s))


Better yet, notice that there are only two cases for altering hours:

def convert_12h_to_24h(s):
"""
Convert a time from a 12-hour format into 24-hour format.

The input should be a 10-character string like "01:23:45PM", and the
output would be "13:23:45".
"""
hours, minutes, seconds, am_pm = s[-10:-8], s[-7:-5], s[-4:-2], s[-2:]
if am_pm == 'PM' and hours != '12':
hours = int(hours) + 12
elif am_pm == 'AM' and hours == '12':
hours = '00'
return f"{hours}:{minutes}:{seconds}"

#s normally is input, but this code will only work with this type of string input
s = "05:43:12AM"
print(convert_12h_to_24h(s))

• Hi thank you for your input, extremely helpful, i will be going over this in detail later for some revision Jun 17 at 10:57
• I think you can avoid the if statements by simply writing hours = int(hours) % 12 + 12*(am_pm == ‘PM’)
– Seb
Jun 29 at 21:29
• (And then use string formatting to enforce double digits of course)
– Seb
Jun 29 at 21:31

In production code you would never manually parse a datetime like that. Instead you would use a round-trip through the datetime built-in:

from datetime import datetime

dt = datetime.strptime('05:43:12PM', '%I:%M:%S%p')
print(dt.strftime('%H:%M:%S'))

• was not aware there was a built in module for it thx. Jun 17 at 11:49