2016-09-27 5 views
0

나는 이에 대한 명확한 답변을 찾고 있습니다. datetime을 사용하는 것에 대한 많은 스레드와 다른 웹 사이트를 읽었지 만, 어떻게 특정 날짜에 대해 사용자에게 묻는 간단한 프로그램을 작성한 다음 그 날짜의 차이를 계산할 수 있습니까? 나는 달과 일을 얻는 방법을 알아내는 것에 매달렸다. . 사용자에게 YY, M, DD의 두 날짜와 출력 날짜 차이를 묻는 방법?

내가 지금까지 무엇을 가지고 : 예를 들어 내가 해 사용자에게 메시지를 표시하려면, 그래서

print ("How old will you be when you graduate?") 
print ("If you want to know, I'll have to ask you a few questions.") 

name = input('What is your name? ') 

bYear = int(input("What year were you born? ")) 

print ("Don't worry. Your information is safe with me.") 

bMonth = int(input("What month were you born? ")) 
bDay = int(input("How about the day you were born? ")) 

print ("Fantastic. We're almost done here.") 

gYear = int(input("What year do you think you'll graduate? ")) 
gMonth = int(input("What about the month? ")) 
gDay = int(input("While you're at it, give me the day too. ")) 


age = gYear - bYear 

if bMonth > gMonth: 
    age = age - 1 
    aMonth = 
if bMonth == gMonth and bDay > gDay: 
    age = age - 1 

print(name, 'you will be', age, 'years old by the time you graduate. Thanks for the information.') 

난 그냥 파이썬을 사용하기 시작하고,하지만 그건 그냥 들어오는 아주 간단 보인다 그들은 그들이 태어난 달, 그리고 그들이 태어난 날. 그런 다음 졸업 할 달, 졸업 할 달, 졸업 할 날을 사용자에게 알리고 싶습니다. 그런 다음 그 날짜의 차이를 계산하여 년, 월, 일로 사람의 나이를 출력하도록 프로그램에 요청합니다. 예를

를 들어

BORN AUGUST 23, 1995 
WILL GRADUATE: JUNE 11, 2018 
AGE AT GRADUATION : 22 YEARS 9 MONTHS AND 18 DAYS 
+0

에 관심이있을 수 있습니다 ['timedelta' 객체 (https://docs.python.org/3/library/datetime.html#timedelta-objects) –

답변

0

당신은 datetimedateutil 모듈을 사용할 수 있습니다. datetime은 Python 표준 라이브러리에 있지만 dateutil은 타사입니다. pip와 함께 설치할 수 있습니다.

from datetime import date 
from dateutil.relativedelta import relativedelta 

birth_date = date(year=1992, month=12, day=21) 
graduation_date = date(year=2016, month=9, day=28) 
diff = relativedelta(graduation_date, birth_date) 

>>> print(diff) 
relativedelta(years=+23, months=+9, days=+7) 
>>> print('AGE AT GRADUATION : {0.years} YEARS {0.months} MONTHS AND {0.days} DAYS'.format(diff)) 
AGE AT GRADUATION : 23 YEARS 9 MONTHS AND 7 DAYS