2014-04-25 2 views
1

나는 사용자가보다 쉽게 ​​살 수 있도록하는 파이썬 모듈에 메서드를 작성하고있다. 이 메서드는 해당 달력에 이벤트를 생성합니다. 사용자가 시작일 또는 체크까지이 날짜가 YYYY-MM-DD 형식으로 또는 날짜 RFC 3339 형식으로되어 있는지 확인하기 위해 만든해야 종료일을 지정하는 경우날짜 형식 Python 추측

def update_event(start_datetime=None, end_datetime=None, description=None): 
''' 
Args: 
    start_date: string datetime in the format YYYY-MM-DD or in RFC 3339 
    end_date: string datetime in the format YYYY-MM-DD or in RFC 3339 
    description: string with description (\n are transforrmed into new lines) 
''' 

.

if (start_date is not None): 
    # Check whether we have an date or datetime value 
    # Whole day events are represented as YYYY-MM-DD 
    # Other events are represented as 2014-04-25T10:47:00.000-07:00 
    whole_day_event = False 
    try: 
     new_start_time = datetime.datetime.strptime(start_date,'YYYY-MM-DD') 
     # Here the event date is updated 
     try: 
      new_start_time = datetime.datetime.strptime(start_date,'%Y-%m-%dT%H:%M:%S%z') 
      #Here the event date is updated 
     except ValueError: 
      return (ErrorCodeWhatever) 
    except ValueError: 
     return (ErrorCodeWhatever) 

이렇게하는 것이 좋은 방법일까요? 더 좋은 방법으로 어떤 날짜를받을 수 있는지 확인할 수 있습니까? 감사합니다.

+0

오류를 '발생'시켜야하며 '반환'하지 마십시오. – Hamish

+0

당신은 절대적으로 옳습니다. 질문을 게시하기위한 코드를 작성하는 중이었습니다 – Jaboto

답변

3

dateutil.parser.parse은 문자열을 datetime 개체로 구문 분석하는 데 사용할 수 있습니다.

from dateutil.parser import parse 

def update_event(start_datetime=None, end_datetime=None, description=None): 
    if start_datetime is not None: 
     new_start_time = parse(start_datetime) 

     return new_start_time 

d = ['23/04/2014', '24-04-2013', '25th April 2014'] 

new = [update_event(i) for i in d] 

for date in new: 
    print(date) 
    # 2014-04-23 00:00:00 
    # 2013-04-24 00:00:00 
    # 2014-04-25 00:00:00 
+0

고마워요! 이 사실을 알지 못했습니다. – Jaboto

+0

아무런 문제가 없기 때문에 기꺼이 도움을 얻을 수 있습니다. 내 대답이 도움이되었다고 생각되면 [내 대답 수락] (http://meta.stackexchange.com/a/5235/192545)을 할 수 있습니다. – Ffisegydd