Skip to content

Commit 467017c

Browse files
committed
update, refactor DateParser
1 parent 979256b commit 467017c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

pydateparser/date_parser.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import attr
2+
from ._loggers import logger
3+
from collections import namedtuple
4+
from .date_formats import DateFormats
5+
from ._errors import DateParserException
6+
from ._core_date_parser import CoreDateParser
7+
from ._validators import _date_format_type_validator, _end_year_validator
8+
9+
10+
@attr.s(slots=True)
11+
class DateParser:
12+
"""
13+
CoreDateParser Adapter class.
14+
"""
15+
text = attr.ib(validator=attr.validators.instance_of(str))
16+
start_year = attr.ib(validator=attr.validators.instance_of(int))
17+
end_year = attr.ib(validator=attr.validators.instance_of(int))
18+
locale = attr.ib(default=None, validator=_date_format_type_validator)
19+
20+
def __attrs_post_init__(self):
21+
object.__setattr__(self, "locale", self.date_format_handler(self.locale))
22+
23+
@staticmethod
24+
def date_format_handler(locale):
25+
if locale == None:
26+
return DateFormats.locale.get('USA')
27+
elif locale != None and isinstance(locale, str) and locale in DateFormats.locale.keys():
28+
return DateFormats.locale.get(locale)
29+
else:
30+
return locale
31+
32+
@staticmethod
33+
def _format_date(date_object):
34+
_date = namedtuple("DATE", ["date", "token_span", "token_index", "format"])
35+
return _date(date_object[0], (date_object[1], date_object[2]),
36+
(date_object[4], date_object[5]), date_object[3])
37+
38+
@staticmethod
39+
def _parser(text, start_year, end_year, locale, formatter):
40+
DP = CoreDateParser(locale, start_year=start_year, end_year=end_year)
41+
try:
42+
logger.info('Extracting dates from the text.')
43+
dt = DP.parse_string(text)
44+
_dt = [formatter(i) for i in dt]
45+
return _dt
46+
except DateParserException:
47+
return None
48+
49+
@property
50+
def date(self):
51+
return self._parser(self.text, self.start_year, self.end_year, self.locale, self._format_date)

0 commit comments

Comments
 (0)