如何使用if和else将24小时时间格式更改为12小时格式?

时间:2017-08-30 13:25:47

标签: python

例如,如果我们输入0010,那么它应该显示12:10 AM,就像它应该显示的每个数字一样。

2 个答案:

答案 0 :(得分:0)

def to_12_hour(ts):
    hr = int(ts[:2])
    mins = int(ts[-2:])

    return "{0}:{1}{2}".format(hr, mins, 'AM' if hr < 12 else 'PM')

答案 1 :(得分:0)

military_times = ['0010', '0125', '1159', '1200', '1201',
'1259', '1344', '1959', '2359']

for item in military_times:
    # time is between 0000 and 0059
    if int(item[0: 2]) == 0:
        t = '12:' + item[2: 4] + ' AM'

    # time is between 1:00 am and 9:59 am
    elif int(item[0: 2]) > 0 and int(item[0: 2]) <= 9:
        t = str(item[1: 2]) + ':' + item[2: 4] + ' AM'

    # time is between 10:00 am and 11:59 am
    elif int(item[0: 2]) > 0 and int(item[0: 2]) <= 11:
        t = str(item[0: 2]) +  ':' + item[2: 4] + ' AM'

    # time is between 12:00 pm and 12:59 pm
    elif int(item[0: 2]) > 0 and int(item[0: 2]) == 12:
        t = str(item[0: 2]) +  ':' + item[2: 4] + ' PM'

    # time is between 12:00 pm and 11:59 pm
    else:
        t = str(int(item[0: 2]) - 12) + ':' + item[2: 4] + ' PM'

    print t

'''
# output
12:10 AM
1:25 AM
11:59 AM
12:00 PM
12:01 PM
12:59 PM
1:44 PM
7:59 PM
11:59 PM
'''