2012-11-25 4 views
1

이제 How do I strtotime in python?을 알아 냈습니다. 빈 날짜가있는 항목을 처리하는보다 우아한 방법이 있다면 strptime()을 시도하면 오류가 발생합니다.이 스크레이퍼에서 빈 값을 처리하는보다 우아한 방법이 있습니까?

warrant_issued = cells[4].get_text().strip() 
try: 
    warrant_issued_no = datetime.strptime(warrant_issued, '%m/%d/%Y') 
except: 
    warrant_issued_no = '' 

이 작동하지만 각 행에 4 ~ 5 날짜를 구문 분석하고 있는데이 말의 반복적 모두 같다. 나는 함수를 정의해야한다고 생각하지만,이 방법을 좀 더 파이썬 적으로 만들어야 할 다른 방법이 있습니까?

처음에는 from datetime import datetime을 입력 했으므로 datetime.strptime()이 작동합니다. 그렇지 않으면 내가 필요 할거야 datetime.datetime.strptime()

답변

1

나는 함수를 정의하고 처리하는 방법을 알고있는 예외만을 잡는 것이 정확하게 이것을하는 방법이라고 생각한다.

def parse_datetime(warrant_issued): 
    try: 
     warrant_issued_no = datetime.strptime(warrant_issued, '%m/%d/%Y') 
    except ValueError: 
     warrant_issued_no = '' 

warrants_issued = [ parse_datetime(cell.get_text().strip()) for cell in cells ] 
+1

이것은 잘못된 날짜 문자열이 모두 "무시"되는 반면 jdotjdot의 솔루션은 빈 문자열 만 무시한다는 약간의 단점이 있습니다. 이것은 OP가 원하는 것일 수도 아닐 수도 있습니다. – Bakuriu

+0

@Bakuriu 나는 예외를 기록하는 것을 실제로 끝내었다. 그래서 나는 그들을 조사 할 수 있었다. 그리고 내가 붙잡을 필요가 있었던 날짜를 놓치지 않았는지 확인했다. – Amanda

0

난 당신이 @mgilson 한 말에 비슷한 일을하고 떨어져 약간 더 나은 것 같아요,하지만 당신은 실수로 오류를 잡을 우려가 있으므로 if 문보다는 try/catch, 당신은에 의미하지 않았다.

제 생각에 여기 잡으려고하는 오류는 날짜 필드가 비어있는 경우입니다. 그래서 그것이 내가 할 일입니다.

def parse_datetime(warrant_issued): 
    # Using Python's "truthiness" to take care of both '' and None, however it comes out 
    if warrant_issued: 
     warrant_issued_no = datetime.strptime(warrant_issued, '%m/%d/%Y') 
    else: 
     warrant_issued_no = '' 

warrants_issued = [parse_datetime(cell.get_text().strip()) for cell in cells] 

이 방법, 당신은 여전히 ​​ValueError를 throw하지만 날짜없는 거기에서, 예외를 던질거야 당신이 알아서 할 수 있습니다하지 않습니다 다른 오류가 끝날 경우 그것.