2013-12-22 6 views
0

사용자 입력으로 날짜를 가져와 날짜 기준으로 두 날짜의 차이를 찾아야합니다. raw_input을 사용하여 날짜를 가져 오려고했지만 오류가 발생했습니다. 파이썬 2.7 버전을 사용하고 있습니다. 양식 "yyyy:mm:dd"에 입력을 기대하는 경우날짜에 따라 사용자 입력으로 날짜를 가져와 두 날짜의 차이를 찾는 방법

import time 
from datetime import date 
day1 = int(raw_input("enter the date in this format (yyyy:mm:dd)") 
day2 = int(raw_input("enter the date in this format (yyyy:mm:dd)") 
diff = day2-day1 
print diff 
+1

['datetime.strptime()']에 대한 문서 읽기 (http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) – jfs

답변

1

, 당신은 단순히 int에 캐스팅 수 없습니다.

strptime 외에도 직접 입력을 구문 분석 할 수 있습니다. 정의하여 @JF 세바스찬, 사용하는 경우에도 간단한 방법 lambda

day1 = [int(i) for i in raw_input('...').split(':')] 
d1 = datetime.date(*day1) 
day2 = [int(i) for i in raw_input('...').split(':')] 
d2 = datetime.date(*day2) 
diff = d2 - d1 
print diff.days 

감사 :

str2date = lambda s: datetime.date(*map(int, s.split(':'))) 

간단히 전화 :

date = str2date(raw_input('...')) 
+0

나는 이것이 주석이어야한다고 생각합니다. . –

+0

@ 내 코드 업데이트. 잠깐만. – Ray

+1

'str2date = lambda : date (* map (int, s.split (':')))' – jfs

2

당신은에 그 날짜를 구문 분석해야합니다 조금 더 의미있는 것. 결과 datetime 개체의

from datetime import datetime 

day1 = raw_input("enter the date in this format (yyyy:mm:dd)") 
day2 = raw_input("enter the date in this format (yyyy:mm:dd)") 
day1 = datetime.strptime(day1, '%Y:%m:%d').date() 
day2 = datetime.strptime(day2, '%Y:%m:%d').date() 
diff = day2 - day1 
print diff.days 

datetime.datetime.date() 메소드가 리턴 단지 날짜 부분 다음 datetime.datetime.strptime() 방법을 사용합니다.

+0

고마워요. – user3126474

관련 문제