Winkleson
Winkleson

Reputation: 203

24-Hour Time Conversion to 12-Hour Clock (ProblemSetQuestion) on Python

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!

Upvotes: 6

Views: 12954

Answers (3)

B_Libs
B_Libs

Reputation: 11

import datetime

hour = datetime.datetime.now().strftime("%H")
minute = datetime.datetime.now().strftime("%M")
if int(hour) > 12:
    hour = int(hour) - 12
    amPm = 'PM'
else:
    amPm = 'AM'
if int(hour) == 12:
    amPm = 'PM'
if int(hour) == 0:
    hour = 12
    amPm = 'AM'
strTime = str(hour) + ":" + minute + " " + amPm
print(strTime)

Take hour and minute from datetime. Convert hour to an int. Check if int(hour) > 12. If so, change from AM to PM. Assign hour with int(hour) - 12. Check if hour is 0 for 12 AM exception. Check if hour is 12 for 12 PM exception. Convert hour back into a string. Print time.

Upvotes: 1

GaretJax
GaretJax

Reputation: 7780

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:

from datetime import datetime

def convertTime(s):
    print datetime.strptime(s, '%H%M').strftime('%I:%M%p').lower()

You can split the input string in the hours and minutes parts in the following way:

hours = input[0:2]
minutes = input[2:4]

And then parse the values to obtain an integer:

hours = int(hours)
minutes = int(minutes)

Or, to do it in a more pythonic way:

hours, minutes = int(input[0:2]), int(input[2:4])

Then you have to decide if the time is in the morning (hours between 0 and 11) or in the afternoon (hours between 12 and 23). Also remember to treat the special case for hours==0:

if hours > 12:
    afternoon = True
    hours -= 12
else:
    afternoon = False
    if hours == 0:
        # Special case
        hours = 12

Now you got everything you need and what's left is to format and print the result:

print '{hours}:{minutes:02d}{postfix}'.format(
    hours=hours,
    minutes=minutes,
    postfix='pm' if afternoon else 'am'
)

Wrap it up in a function, take some shortcuts, and you're left with the following result:

def convertTime(input):
    h, m = int(input[0:2]), int(input[2:4])

    postfix = 'am'

    if h > 12:
        postfix = 'pm'
        h -= 12

    print '{}:{:02d}{}'.format(h or 12, m, postfix)

convertTime('0000') 
convertTime('1337') 
convertTime('0429') 
convertTime('2359') 
convertTime('1111') 

Results in:

12:00am
1:37pm
4:29am
11:59pm
11:11am

Upvotes: 10

arynaq
arynaq

Reputation: 6870

Some tips int("2300") returns an integer 2300 2300 is PM. time >= 1200 is PM time between 0000 and 1200 is AM.

You could make a function that takes a string, evaluates it as integer, then checks if it is greater or less than the above conditions and returns a print.

Upvotes: 2

Related Questions