ProgramingTip

파이썬의 날짜에서 날짜 추출

bestdevel 2020. 11. 22. 20:21
반응형

파이썬의 날짜에서 날짜 추출


"monkey 2010-07-10 love banana"와 같은 날짜에서 날짜를 어떻게 추출 할 수 있습니까? 감사합니다!


날짜가 고정 형식으로 제공되는 경우 정규식을 사용하여 날짜를 추출하고 "datetime.datetime.strptime"을 사용하여 날짜를 구문 분석 할 수 있습니다.

match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()

꽃다발 날짜가 임의의 형식으로 주어지면 쉽게 추출 할 수 없습니다.


사용 가능한 dateutil를 :

In [1]: import dateutil.parser as dparser

In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True)
Out[18]: datetime.datetime(2010, 7, 10, 0, 0)

잘못된 날짜 발생 ValueError:

In [19]: dparser.parse("monkey 2010-07-32 love banana",fuzzy=True)
# ValueError: day is out of range for month

다양한 형식의 날짜를 인식 할 수 있습니다.

In [20]: dparser.parse("monkey 20/01/1980 love banana",fuzzy=True)
Out[20]: datetime.datetime(1980, 1, 20, 0, 0)

날짜가 모호한 경우 추측을합니다.

In [23]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True)
Out[23]: datetime.datetime(1980, 10, 1, 0, 0)

그러나 모호한 날짜를 구문 분석하는 방법은 사용자 정의 할 수 있습니다.

In [21]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True, dayfirst=True)
Out[21]: datetime.datetime(1980, 1, 10, 0, 0)

파이썬의 날짜에서 날짜를 추출합니다. 사용 가능한 최고의 모듈은 datefinder 모듈입니다.

아래 주어진 간단한 단계에 따라 Python 프로젝트에서 사용할 수 있습니다.

1 단계 : datefinder 패키지 설치

pip install datefinder

2 단계 : 프로젝트에서 사용

import datefinder

input_string = "monkey 2010-07-10 love banana"
# a generator will be returned by the datefinder module. I'm typecasting it to a list. Please read the note of caution provided at the bottom.
matches = list(datefinder.find_dates(input_string))

if len(matches) > 0:
    # date returned will be a datetime.datetime object. here we are only using the first match.
    date = matches[0]
    print date
else:
    print 'No dates found'

참고 : 많은 수의 일치가 예상되는 경우; 그렇게 목록에 대한 형변환은 성능 오버 헤드가 크기 때문에 권장되는 방법이 아닙니다.


Pygrok를 사용하면 정규식 구문에 대한 추상화 된 확장을 정의 할 수 있습니다.

사용자 지정 패턴은 형식으로 정규식에 사용 가능 %{PATTERN_NAME}합니다.

콜론으로 구분하여 해당 패턴에 대한 레이블을 만들 수도 있습니다 %s{PATTERN_NAME:matched_string}.. 패턴과 일치하는 경우, 값이 사전 생성의 일부로서 리턴 (예 result.get('matched_string'))

예를 들면 :

from pygrok import Grok

input_string = 'monkey 2010-07-10 love banana'
date_pattern = '%{YEAR:year}-%{MONTHNUM:month}-%{MONTHDAY:day}'

grok = Grok(date_pattern)
print(grok.match(input_string))

결과 값은 사전이됩니다.

{'month': '07', 'day': '10', 'year': '2010'}

date_pattern이 input_string에 없으면 반환 값은 None. 반대로 패턴에 레이블이없는 경우 빈 사전을 반환합니다.{}

참조 :


문자열 (예 : 로그 파일)에서 날짜 객체의 위치를 ​​알고있는 경우 .split () [index]를 사용하여 형식을 완전히 몰라도 날짜를 추출 할 수 있습니다.

예를 들면 :

>>> string = 'monkey 2010-07-10 love banana'
>>> date = string.split()[1]
>>> date
'2010-07-10'

참고 URL : https://stackoverflow.com/questions/3276180/extracting-date-from-a-string-in-python

반응형