【파이썬 CheckiO 题 解】 날짜 및 시간 계산기


CheckiO는,이 블로그는 파이썬에서 할을 자신의 생각을 기록하기 위해 주로하여 코딩 능력을 향상 코드 게임, 주소 어려운 도전에 파이썬과 자바 스크립트와 흥미로운 작업 초보자 및 고급 프로그래머를위한 체크 포인트 및 구현 코드에서 문제 다른 위대한 하나님이 코드를 작성에서뿐만 아니라 배운다.

CheckiO 공식 웹 사이트 : https://checkio.org/

내 CheckiO 홈 : https://py.checkio.org/user/TRHX/

열 CheckiO 문제 솔루션 시리즈 : https://itrhx.blog.csdn.net/category_9536424.html

CheckiO 문제 소스에 대한 모든 솔루션 : https://github.com/TRHX/Python-CheckiO-Exercise


제목 설명

[날짜 및 시간 변환기] : 컴퓨터의 날짜 및 시간 형식은 예를 들어, 숫자로만 구성 :21.05.2018 16:30사람들이이 같은 것을 볼 것을 선호합니다 :21 May 2018 year 16 hours 30 minutes당신의 임무는 사람들이 날짜 형식으로 선호하는 컴퓨터 형식으로 날짜를 변환하는 것입니다.

그림 삽입 설명 여기
【链接】 : https://py.checkio.org/mission/date-and-time-converter/

[입력] : 날짜 및 시간 형식 컴퓨터 (문자열)

[출력] : 명 (문자열) 날짜 형식으로 선호

【前提】 : 0 <날짜 <= 31; 0 <달 <= 12; 0 <년 <= 3000 0 <시간 <24, 0 <분 <60

[실시 예] :

date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes"
date_time("19.09.2999 01:59") == "19 September 2999 year 1 hour 59 minutes"
date_time("21.10.1999 18:01") == "21 October 1999 year 18 hours 1 minute"
NB: words "hour" and "minute" are used only when time is 01:mm (1 hour) or hh:01 (1 minute).
In other cases it should be used "hours" and "minutes".

문제 해결 아이디어

시간과 분 1 인 경우, 그 다음 우리가 사용하는 것이라고, 주목해야한다 hourminute다른 경우에 사용 hours하고 minutes,

또한, 일,시, 분, 일본어 캐릭터 전환 1 (0 제거 전면)는 다음 후 01 인 경우;

원래의 문자열은 문자열리스트 형태로 전환하는 공간 분할 인 분리 소수점 대장을 제거하는 처리;

달이와 영어의 목록이 표시되는 int()방법을 초과 숫자 0을 제거하는 일에 의해 원래의 문자열을 대체하고, 마지막으로 새로운 문자열로 접합 할 수있다.

코드 구현

def date_time(time: str) -> str:
    month = ['January', 'February', 'March', 'April', 'May',
             'June', 'July', 'August', 'September', 'October',
             'November', 'December']
    time = time.replace('.', ' ').replace(':', ' ').split()
    time[0] = str(int(time[0]))
    time[1] = month[int(time[1])-1]
    time[2] = time[2] + ' year'
    if time[3] == '01':
        time[3] = '1 hour'
    else:
        time[3] = str(int(time[3])) + ' hours'
    if time[4] == '01':
        time[4] = '1 minute'
    else:
        time[4] = str(int(time[4])) + ' minutes'
    time = ' '.join(time)
    return time


if __name__ == '__main__':
    print("Example:")
    print(date_time('01.01.2000 00:00'))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium"
    assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory"
    assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born"
    print("Coding complete? Click 'Check' to earn cool rewards!")

테라스 해답

테라스 해답 NO.1

from datetime import datetime

def checkio(time):
    dt = datetime.strptime(time, '%d.%m.%Y %H:%M')
    hour = 'hour' if dt.hour == 1 else 'hours'    
    minute = 'minute' if dt.minute == 1 else 'minutes'
    return dt.strftime(f'%-d %B %Y year %-H {hour} %-M {minute}')

테라스 해답 NO.2

from datetime import datetime


def date_time(time):
    t = datetime.strptime(time, '%d.%m.%Y %H:%M')
    y, m, d, h, mi =  t.year, datetime.strftime(t, '%B'), t.day, t.hour, t.minute
    suffix = lambda n: 's' if n != 1 else ''
    return f'{d} {m} {y} year {h} hour{suffix(h)} {mi} minute{suffix(mi)}'

테라스 해답 NO.3

from datetime import datetime

def checkio(dt):
    dt = datetime.strptime(dt, '%d.%m.%Y %H:%M')
    p = lambda attr: attr + 's' * (getattr(dt, attr) != 1)
    return dt.strftime(f'%-d %B %Y year %-H {p("hour")} %-M {p("minute")}')
게시 된 149 개 원래 기사 · 원 찬양 (518) ·은 460,000 + 조회수

추천

출처blog.csdn.net/qq_36759224/article/details/103647196