취미생활/CheckIO

[checkIO]Home 04.Time Converter (24h to 12h)

우주먼지의하루 2020. 2. 11. 10:50
728x90

You prefer a good old 12-hour time format. But the modern world we live in would rather use the 24-hour format and you see it everywhere. Your task is to convert the time from the 24-h format into 12-h format by following the next rules:

- the output format should be 'hh:mm a.m.' (for hours before midday) or 'hh:mm p.m.' (for hours after midday)

- if hours is less than 10 - don't write a '0' before it. For example: '9:05 a.m.'

Here you can find some useful information about the 12-hour format.

Input: Time in a 24-hour format (as a string).

Output: Time in a 12-hour format (as a string).

Example:

time_converter('12:30') == '12:30 p.m.'

time_converter('09:00') == '9:00 a.m.'

time_converter('23:15') == '11:15 p.m.'

* 24시 포멧에서 12시 포멧으로 바꾸기.

* 출력 형식은 hh:mm am 이나 hh:mm pm으로 한다.

* 10시 미만인 경우 앞에 0을 빼고 출력한다.

 

- 풀이 1

 

def time_converter(time):
    
    time=time.split(":")
    
    if int(time[0]) > 12:
        time[0]=int(time[0])- 12
        time[0]=str(time[0])
        time = ":".join(time)
        
        return time + " p.m."
        
    elif int(time[0]) == 12:
        time = ":".join(time)
        return time + " p.m."
        
    elif time[0] == "00":
        return "12:00 a.m."  
          
    else:
        if int(time[0]) < 10:
            time = ":".join(time)
            return time[1:]+" a.m."
        else:
            time = ":".join(time)
            return time+ " a.m."

 

 

- 풀이 2

def time_converter(time):
    h, m = map(int, time.split(':'))
    if h < 12:
        ampm = 'a.m.'
    else:
        ampm = 'p.m.'
    if h > 12:
        h -= 12
    elif h == 0:
        h = 12
    return '%d:%02d %s' % (h, m, ampm)
반응형