I am a beginner programmer in Python and I have no idea how to proceed with the following question. There are a ton of similar questions out there, however there are none having to do with Python code.
I have tried to compare the strings but I am uncertain how to make the comparison. I’m pretty sure I need to take the first two numbers (hours) and divide by 12 if it is greater than 12 … but that presents problems.
Question:
Time Conversion (24hrs to 12hr)
Write a function that will allow the
user to convert the 24 hour time format to the 12 hour format (with
‘am’,’pm’ attached). Example: from ‘1400’ to ‘2:00pm’. All strings
passed in as a parameter will have the length of 4 and will only
contain numbers.
Examples (tests/calls):
>>> convertTime('0000')
'12:00am'
>>> convertTime('1337')
'1:37pm'
>>> convertTime('0429')
'4:29am'
>>> convertTime('2359')
'11:59pm'
>>> convertTime('1111')
'11:11am'
Any input or different methods would be awesome!
You could use the datetime module, but then you would have to deal with dates as well (you can insert wathever you want there). Probably easier to simply parse it.
Update: As @JonClements pointed out in the comments to the original question, it can be done with a one liner:
You can split the input string in the hours and minutes parts in the following way:
And then parse the values to obtain an integer:
Or, to do it in a more pythonic way:
Then you have to decide if the time is in the morning (
hoursbetween 0 and 11) or in the afternoon (hoursbetween 12 and 23). Also remember to treat the special case forhours==0:Now you got everything you need and what’s left is to format and print the result:
Wrap it up in a function, take some shortcuts, and you’re left with the following result:
Results in: