Pyschools时间转换

时间:2017-03-15 08:09:56

标签: python python-2.7 time

军事到常规时间转换

所以,我对这个练习有问题,我必须转换时间,让AM和PM进入上午和下午。

编写一个将时间从军事格式转换为常规格式的函数。 例子:

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

首先尝试:

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

这将返回'12:00 PM'这是好的,但是pyschools要求PM为p.m.或AM进入a.m.和13:01应该返回1:01而不是01:01。

第二次尝试:

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.

我的代码中出错了什么?

1 个答案:

答案 0 :(得分:1)

好的,所以我解决了。 这是正确的答案:

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.'
)