alex
alex

Reputation: 2541

Pyschools time conversion

Military To Regular Time Conversion

So, i have a problem with this exercise, I have to convert the time and make AM and PM into a.m. and p.m.

Write a function that converts the time from military to regular format. Examples:

>>> time12hr('1619')
    '4:19 p.m.'
>>> time12hr('1200')
    '12:00 p.m.'
>>> time12hr('1020')
    '10:20 a.m.'

First try:

from datetime import datetime

def time12hr(the_time):
    hour = the_time[0:2]        

    d = datetime.strptime(the_time, "%H%M")
    s = d.strftime("%I:%M %p")
    return s

Test Cases         Expected Result  Returned Result
time12hr('1202')     12:02 p.m.       12:02 PM  
time12hr('1200')     12:00 p.m.       12:00 PM  
time12hr('0059')     12:59 a.m.       12:59 AM  
time12hr('1301')      1:01 p.m.       01:01 PM
time12hr('0000')     12:00 a.m.       12:00 AM

This returns '12:00 PM' which is good but pyschools requires PM to be p.m. or AM into a.m. and 13:01 should be returned 1:01 not 01:01.

Second try:

from datetime import datetime

def time12hr(input):
    hours, minutes = int(input[0:2]), int(input[2:4])
    if hours > 12:
            afternoon = True
            hours -= 12
    else:
            afternoon = False
        if hours == 0:
            # Special case
            hours = 12
        return '{hours}:{minutes:02d} {postfix}'.format(
    hours=hours,
    minutes=minutes,
    postfix='p.m.' if afternoon else 'a.m.'
)


Test Cases         Expected Result  Returned Result 
time12hr('1202')    12:02 p.m.        12:02 a.m.    - this is not good
time12hr('1200')    12:00 p.m.        12:00 a.m.    - this is not good
time12hr('0059')    12:59 a.m.        12:59 a.m.    
time12hr('1301')    1:01 p.m.          1:01 p.m.    
time12hr('0000')    12:00 a.m.        12:00 a.m.

What am i doing wrong in my code?

Upvotes: 0

Views: 262

Answers (1)

alex
alex

Reputation: 2541

Ok so i solved it. This is the correct answer:

from datetime import datetime

def time12hr(input):
    hours, minutes = int(input[0:2]), int(input[2:4])
    if hours >= 12:
            afternoon = True
            hours -= 12
    else:
            afternoon = False
        if hours == 0:
            hours = 12

        return '{hours}:{minutes:02d} {postfix}'.format(
    hours=hours,
    minutes=minutes,
    postfix='p.m.' if afternoon else 'a.m.'
)

Upvotes: 1

Related Questions