patternpythonModerate
12 hours to 24 hours conversion function
Viewed 0 times
hoursconversionfunction
Problem
I have made a time format converter which converts 12 hour format to 24 hour format. My
Note: Let us assume that input will always have no space between them e.g.
Sample usage:
Can my function be made even better? By better I mean better in way of performance, design etc.
convert_to_24() takes a string in format of HH:MM:SS followed by AM or PM. It returns a converted string to 24 hours format without the AM/PM string.Note: Let us assume that input will always have no space between them e.g.
07:05:45PM, not 07:05:45 PMdef convert_to_24(time):
"""str -> str
converts 12 hours time format to 24 hours
"""
return time[:-2] if time[-2:] == "AM" else str(int(time[:2]) + 12) + time[2:8]Sample usage:
>>> convert_to_24("07:05:45PM")
'19:05:45'
>>> convert_to_24("10:47:00PM")
'22:47:00'
>>> convert_to_24("02:35:36AM")
'02:35:36'
>>>Can my function be made even better? By better I mean better in way of performance, design etc.
Solution
This function is not just cryptic — it's also wrong. I would expect
convert_to_24('12:00:00AM') (midnight) to be '00:00:00', but it returns '12:00:00' (noon).Context
StackExchange Code Review Q#111596, answer score: 11
Revisions (0)
No revisions yet.