dateparser package
Subpackages
Submodules
dateparser.conf module
- exception dateparser.conf.SettingValidationError[source]
Bases:
ValueError
- class dateparser.conf.Settings(settings: Mapping[str, Any] | None = None)[source]
Bases:
objectControl and configure default parsing behavior of dateparser. Currently, supported settings are:
DATE_ORDER
PREFER_LOCALE_DATE_ORDER
STRICT_DATE_ORDER
TIMEZONE
TO_TIMEZONE
RETURN_AS_TIMEZONE_AWARE
TIMEZONE_ABBREVIATIONS
PREFER_MONTH_OF_YEAR
PREFER_DAY_OF_MONTH
PREFER_DATES_FROM
RELATIVE_BASE
STRICT_PARSING
REQUIRE_PARTS
IGNORE_SURROUNDING_TEXT
SKIP_TOKENS
NORMALIZE
RETURN_TIME_AS_PERIOD
RETURN_TIME_SPAN
DEFAULT_START_OF_WEEK
DEFAULT_DAYS_IN_MONTH
PARTS_OF_DAY
PARSERS
DEFAULT_LANGUAGES
USE_GIVEN_LANGUAGE_ORDER
LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD
CACHE_SIZE_LIMIT
- PARTS_OF_DAY: PartsOfDay
dateparser.date module
- class dateparser.date.DateData(*, date_obj: datetime | None = None, period: str | None = None, locale: str | None = None, parts: tuple[str, ...] = ())[source]
Bases:
objectClass that represents the parsed data with useful information. It can be accessed with square brackets like a dict object.
- part_of_day: PartOfDay | None = None
PartOfDaythat the date string refers to, e.g.NIGHTfor"tonight", orNone.Added in version 1.5.0.
Its time comes from the
PARTS_OF_DAYsetting, unless the date string also has a time, e.g."tonight at 11pm". If it does not, and theRETURN_TIME_AS_PERIODsetting is enabled,periodis"part_of_day".
- parts
Parts of
date_objdetermined by the parsed string, as a tuple with some or all of"year","month","day"and"time", in that order. The remaining parts come from Settings, e.g.RELATIVE_BASEorPREFER_DAY_OF_MONTH.
- relative_delta: RelativeDelta | None = None
RelativeDeltathat the parsed date string adds to the current date, e.g.RelativeDelta(hours=-2)for"2 hours ago", orNonefor other date strings, e.g."next monday".Added in version VERSION.
A time of day, e.g.
"2 days ago at 5pm", or day of the month, e.g."15 in 2 months", is set ondate_objand is not part of the delta.
- class dateparser.date.DateDataParser(languages: Iterable[str] | None = None, locales: Iterable[str] | None = None, region: str | None = None, try_previous_locales: bool = False, use_given_order: bool = False, settings: Settings | dict[str, Any] | None = None, detect_languages_function: Callable[[...], list[str]] | None = None)[source]
Bases:
objectClass which handles language detection, translation and subsequent generic parsing of string representing date and/or time.
- Parameters:
languages (list) – A list of language codes, e.g. [‘en’, ‘es’, ‘zh-Hant’]. If locales are not given, languages and region are used to construct locales for translation.
locales (list) – A list of locale codes, e.g. [‘fr-PF’, ‘qu-EC’, ‘af-NA’]. The parser uses only these locales to translate date string.
region (str) – A region code, e.g. ‘IN’, ‘001’, ‘NE’. If locales are not given, languages and region are used to construct locales for translation.
try_previous_locales (bool) – If True, locales previously used to translate date are tried first.
use_given_order (bool) – If True, locales are tried for translation of date string in the order in which they are given. This is equivalent to the
USE_GIVEN_LANGUAGE_ORDERsetting; the given order is preserved if either is enabled.settings (dict) – Configure customized behavior using settings defined in
dateparser.conf.Settings.detect_languages_function (function) – A function for language detection that takes as input a text and a confidence_threshold, and returns a list of detected language codes. Note: this function is only used if
languagesandlocalesare not provided.
- Returns:
A parser instance
- Raises:
ValueError: Unknown Language,TypeError: Languages argument must be a list,SettingValidationError: A provided setting is not valid.
- get_date_data(date_string: str, date_formats: Iterable[str] | None = None) DateData[source]
Parse string representing date and/or time in recognizable localized formats. Supports parsing multiple languages and timezones.
- Parameters:
date_string (str) – A string representing date and/or time in a recognizably valid format.
date_formats (list) – A list of format strings using directives as given here. The parser applies formats one by one, taking into account the detected languages. A UTC offset matched by
%zis kept, while a time zone name matched by%Zis ignored. If no format matches, the other parsers of the PARSERS setting are tried; set it to['custom-formats']to use only these formats.
- Returns:
a
DateDataobject.- Raises:
ValueError - Unknown Language
Note
Period values can be a ‘day’ (default), ‘week’, ‘month’, ‘quarter’, ‘year’, ‘time’, ‘part_of_day’.
Period represents the granularity of date parsed from the given string.
In the example below, since no day information is present, the day is assumed to be current day
16from current date (which is June 16, 2015, at the moment of writing this). Hence, the level of precision ismonth:>>> DateDataParser().get_date_data('March 2015') DateData(date_obj=datetime.datetime(2015, 3, 16, 0, 0), period='month', locale='en', parts=('year', 'month'))
Similarly, for date strings with no day and month information present, level of precision is
yearand day16and month6are from current_date.>>> DateDataParser().get_date_data('2014') DateData(date_obj=datetime.datetime(2014, 6, 16, 0, 0), period='year', locale='en', parts=('year',))
Parts lists the parts of the date that the given string determines, including those that period cannot tell apart, like a missing year:
>>> DateDataParser().get_date_data('16 March') DateData(date_obj=datetime.datetime(2015, 3, 16, 0, 0), period='day', locale='en', parts=('month', 'day'))
Dates with time zone indications or UTC offsets are returned in UTC time unless specified using Settings.
>>> DateDataParser().get_date_data('23 March 2000, 1:21 PM CET') DateData(date_obj=datetime.datetime(2000, 3, 23, 13, 21, tzinfo=<StaticTzInfo 'CET'>), period='day', locale='en', parts=('year', 'month', 'day', 'time'))
- locale_loader: LocaleDataLoader | None = None
- previous_locales: collections.OrderedDict[Locale, None]
- dateparser.date.get_date_from_timestamp(date_string: str, settings: Settings | None, negative: bool = False) datetime | None[source]
- dateparser.date.get_intersecting_periods(low: _D, high: _D, period: str = 'day') Iterator[_D][source]
dateparser.date_parser module
dateparser.freshness_date_parser module
- class dateparser.freshness_date_parser.FreshnessDateDataParser[source]
Bases:
objectParses date string like “1 year, 2 months ago” and “3 hours, 50 minutes ago”.
- class dateparser.freshness_date_parser.RelativeDelta(years: float = 0, months: float = 0, weeks: float = 0, days: float = 0, hours: float = 0, minutes: float = 0, seconds: float = 0)[source]
Bases:
objectOffset from the current date that a relative date string expresses, e.g.
RelativeDelta(hours=-2)for"2 hours ago".Added in version VERSION.
dateparser.search module
- dateparser.search.search_dates(text: str, languages: Iterable[str] | None = None, settings: Settings | dict[str, Any] | None = None, add_detected_language: bool = False, detect_languages_function: Callable[[...], list[str]] | None = None, strategy: str = 'split', date_formats: Iterable[str] | None = None, add_period: bool = False) list[tuple[str, datetime]] | list[tuple[str, datetime, str | None]] | list[tuple[str, datetime, str | None, str | None]] | None[source]
Find all substrings of the given string which represent date and/or time and parse them.
- Parameters:
text (str) – A string in a natural language which may contain date and/or time expressions.
languages (list) – A list of two letters language codes.e.g. [‘en’, ‘es’]. If languages are given, it will not attempt to detect the language.
settings (dict) – Configure customized behavior using settings defined in
dateparser.conf.Settings.add_detected_language (bool) – Indicates if we want the detected language returned in the tuple.
detect_languages_function (function) – A function for language detection that takes as input a text and a confidence_threshold, and returns a list of detected language codes. Note: detect_languages_function is only uses if languages are not provided.
strategy (str) – The search strategy to use: “split” (default) translates the text and splits it into chunks that are likely to contain dates, while “ngram” tries to parse the longest possible sequences of tokens as dates. The “ngram” strategy tends to produce more predictable results, at the cost of more parse attempts.
date_formats (list) – A list of format strings. Text that matches any of them is found before the rest of the text is searched, as long as it does not start or end with whitespace or any of
,|()@. Requiresstrategy="ngram".add_period (bool) –
Indicates if we want the period of each date (
time,part_of_day,day,week,monthoryear) returned in the tuple, before the detected language.timeandpart_of_dayrequire theRETURN_TIME_AS_PERIODsetting.Added in version 1.5.0.
- Returns:
Returns list of tuples containing: substrings representing date and/or time, corresponding
datetime.datetimeobject, period if add_period is True and detected language if add_detected_language is True. Returns None if no dates that can be parsed are found.- Return type:
- Raises:
ValueError - Unknown Language
>>> from dateparser.search import search_dates >>> search_dates('The first artificial Earth satellite was launched on 4 October 1957.') [('on 4 October 1957', datetime.datetime(1957, 10, 4, 0, 0))]
>>> search_dates('The first artificial Earth satellite was launched on 4 October 1957.', >>> add_detected_language=True) [('on 4 October 1957', datetime.datetime(1957, 10, 4, 0, 0), 'en')]
>>> search_dates("The client arrived to the office for the first time in March 3rd, 2004 " >>> "and got serviced, after a couple of months, on May 6th 2004, the customer " >>> "returned indicating a defect on the part") [('in March 3rd, 2004 and', datetime.datetime(2004, 3, 3, 0, 0)), ('on May 6th 2004', datetime.datetime(2004, 5, 6, 0, 0))]
- dateparser.search.search_first_date(text: str, languages: Iterable[str] | None = None, settings: Settings | dict[str, Any] | None = None, add_detected_language: bool = False, detect_languages_function: Callable[[...], list[str]] | None = None, strategy: str = 'split', date_formats: Iterable[str] | None = None, add_period: bool = False) tuple[str, datetime] | tuple[str, datetime, str | None] | tuple[str, datetime, str | None, str | None] | None[source]
Return the first item that
search_dates()would return for the same arguments, orNoneif it would returnNone.Added in version VERSION.
The search stops at the first date found, so it is faster than
search_dates()on text with more dates after the first one.>>> from dateparser.search import search_first_date >>> search_first_date('Launched on 4 October 1957, it fell on 4 January 1958.') ('on 4 October 1957', datetime.datetime(1957, 10, 4, 0, 0))
dateparser.timezone_parser module
- class dateparser.timezone_parser.StaticTzInfo(name: str, offset: timedelta)[source]
Bases:
tzinfo
- dateparser.timezone_parser.convert_to_local_tz(datetime_obj: datetime, datetime_tz_offset: timedelta) datetime[source]
- dateparser.timezone_parser.is_timezone_token(token: str) bool[source]
Whether
tokenis, on its own, a recognized timezone abbreviation.Unlike
word_is_tz()(a case-sensitive prefix match used while scanning original-cased text), this trims surrounding whitespace and does a case-insensitive full match, so it recognizes an already-lowercased, space-padded token such as" est". Because the match is anchored, an ordinary word that merely begins with a timezone abbreviation is not treated as a timezone (e.g."actualisé"is not theACTzone). This is used only on single edge tokens, so the trailing.*in the UTC/GMT numeric-offset patterns (which a full match would otherwise let absorb following text) is not a concern here.
- dateparser.timezone_parser.pop_tz_offset_from_string(date_string: str, as_offset: Literal[True] = True, settings: Settings | None = None) tuple[str, StaticTzInfo | None][source]
- dateparser.timezone_parser.pop_tz_offset_from_string(date_string: str, as_offset: Literal[False], settings: Settings | None = None) tuple[str, str | None]
dateparser.timezones module
dateparser.utils module
- dateparser.utils.apply_dateparser_timezone(utc_datetime: datetime, offset_or_timezone_abb: str) datetime | None[source]
- dateparser.utils.apply_timezone_from_settings(date_obj: datetime, settings: Settings | None) datetime[source]
- dateparser.utils.combine_dicts(primary_dict: Mapping[str, Any], supplementary_dict: Mapping[str, Any]) OrderedDict[str, Any][source]
- dateparser.utils.normalize_unicode(string: str, form: Literal['NFC', 'NFD', 'NFKC', 'NFKD'] = 'NFKD') str[source]
- dateparser.utils.set_correct_day_from_settings(date_obj: datetime, settings: Settings, current_day: int | None = None) datetime[source]
Set correct day attending the PREFER_DAY_OF_MONTH setting.
Module contents
- dateparser.parse(date_string: str, date_formats: Iterable[str] | None = None, languages: Iterable[str] | None = None, locales: Iterable[str] | None = None, region: str | None = None, settings: Settings | dict[str, Any] | None = None, detect_languages_function: Callable[[...], list[str]] | None = None) datetime | None[source]
Parse date and time from given date string.
- Parameters:
date_string (str) – A string representing date and/or time in a recognizably valid format.
date_formats (list) –
A list of format strings using directives as given here. The parser applies formats one by one, taking into account the detected languages/locales. A UTC offset matched by
%zis kept, while a time zone name matched by%Zis ignored. If no format matches, the other parsers of the PARSERS setting are tried; set it to['custom-formats']to use only these formats.languages (list) – A list of language codes, e.g. [‘en’, ‘es’, ‘zh-Hant’]. If locales are not given, languages and region are used to construct locales for translation.
locales (list) – A list of locale codes, e.g. [‘fr-PF’, ‘qu-EC’, ‘af-NA’]. The parser uses only these locales to translate date string.
region (str) – A region code, e.g. ‘IN’, ‘001’, ‘NE’. If locales are not given, languages and region are used to construct locales for translation.
settings (dict) – Configure customized behavior using settings defined in
dateparser.conf.Settings.detect_languages_function (function) – A function for language detection that takes as input a string (the date_string) and a confidence_threshold, and returns a list of detected language codes. Note: this function is only used if
languagesandlocalesare not provided.
- Returns:
Returns
datetimerepresenting parsed date if successful, else returns None- Return type:
- Raises:
ValueError: Unknown Language,TypeError: Languages argument must be a list,SettingValidationError: A provided setting is not valid.
- dateparser.parse_many(date_strings: Iterable[str], languages: list[str] | None = None, locales: list[str] | None = None, region: str | None = None, settings: dict[str, Any] | None = None, detect_languages_function: Callable[[str, float], list[str]] | None = None, max_pending: int | None = None, date_orders: Iterable[str] | None = None) Iterator[datetime | None][source]
Parse date_strings with the date order that fits all of them.
Returns an iterator of
datetimeobjects. For example, in['2015/2/3', '2015/31/12'], the second date string shows that the first one is 2 March 2015, whileparse()would read it as 3 February 2015. Date strings that cannot be parsed becomeNone. Date strings that fit none of the date orders that fit the previous ones are parsed with theDATE_ORDERsetting set to the date order of the others, so theSTRICT_DATE_ORDERsetting decides whether they becomeNone. Neither counts when finding the date order.date_orders limits the candidate date orders, e.g. to
["DMY", "MDY"]to only tell days and months apart. By default, all date orders are candidates.Date strings that different date orders parse differently stay pending until a later date string settles the date order, so input that settles it late keeps many date strings in memory. Shuffling the input, where feasible, helps. Date strings still pending when the input ends, or once more than max_pending are pending, are parsed as
parse()would if that fits one of the date orders that fit the other date strings, and with one of those date orders otherwise.