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: object

Control 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

CACHE_SIZE_LIMIT: int
DATE_ORDER: str
DEFAULT_DAYS_IN_MONTH: int
DEFAULT_LANGUAGES: list[str]
DEFAULT_START_OF_WEEK: str
IGNORE_SURROUNDING_TEXT: bool
LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD: float
NORMALIZE: bool
PARSERS: list[str]
PARTS_OF_DAY: PartsOfDay
PREFER_DATES_FROM: str
PREFER_DAY_OF_MONTH: str
PREFER_LOCALE_DATE_ORDER: bool
PREFER_MONTH_OF_YEAR: str
RELATIVE_BASE: datetime | Literal[False]
REQUIRE_PARTS: list[str]
RETURN_AS_TIMEZONE_AWARE: bool | Literal['default']
RETURN_TIME_AS_PERIOD: bool
RETURN_TIME_SPAN: bool
SKIP_TOKENS: list[str]
STRICT_DATE_ORDER: str
STRICT_PARSING: bool
TIMEZONE: str
TIMEZONE_ABBREVIATIONS: Mapping[str, timedelta]
TO_TIMEZONE: str | Literal[False]
USE_GIVEN_LANGUAGE_ORDER: bool
classmethod get_key(settings: Mapping[str, Any] | None = None) → str[source]
replace(mod_settings: Mapping[str, Any] | None = None, **kwds: Any) → Settings[source]
dateparser.conf.apply_settings(f: Callable[[_P], _R]) → Callable[[_P], _R][source]
dateparser.conf.check_settings(settings: Settings) → None[source]

Check if provided settings are valid, if not it raises SettingValidationError. Only checks for the modified settings.

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: object

Class 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

PartOfDay that the date string refers to, e.g. NIGHT for "tonight", or None.

New in version 1.5.0.

Its time comes from the PARTS_OF_DAY setting, unless the date string also has a time, e.g. "tonight at 11pm". If it does not, and the RETURN_TIME_AS_PERIOD setting is enabled, period is "part_of_day".

parts

Parts of date_obj determined 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_BASE or PREFER_DAY_OF_MONTH.

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: object

Class 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_ORDER setting; 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 languages and locales are 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 %z is kept, while a time zone name matched by %Z is 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 DateData object.

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 16 from current date (which is June 16, 2015, at the moment of writing this). Hence, the level of precision is month:

>>> 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 year and day 16 and month 6 are 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'))
get_date_tuple(*args: Any, **kwargs: Any) → tuple[Any, ...][source]
locale_loader: LocaleDataLoader | None = None
dateparser.date.date_range(begin: _D, end: _D, **kwargs: Any) → Iterator[_D][source]
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.parse_with_formats(date_string: str, date_formats: Iterable[str], settings: Settings) → DateData[source]

Parse with formats and return a dictionary with ‘period’ and ‘obj_date’.

Returns:

datetime.datetime, dict or None

dateparser.date.sanitize_date(date_string: str) → str[source]
dateparser.date.sanitize_spaces(date_string: str) → str[source]

dateparser.date_parser module

class dateparser.date_parser.DateParser[source]

Bases: object

parse(date_string: str, parse_method: Callable[[...], tuple[datetime, str | None] | tuple[datetime, str | None, tuple[str, ...]]], settings: Settings | dict[str, Any] | None = None, date_order: str | None = None) → tuple[datetime, str | None][source]

dateparser.freshness_date_parser module

class dateparser.freshness_date_parser.FreshnessDateDataParser[source]

Bases: object

Parses date string like “1 year, 2 months ago” and “3 hours, 50 minutes ago”.

get_date_data(date_string: str, settings: Settings) → DateData[source]
get_kwargs(date_string: str) → tuple[dict[str, float], dict[str, bool]] | dict[str, float][source]
get_local_tz() → tzinfo[source]
parse(date_string: str, settings: Settings) → tuple[datetime | None, str | None][source]

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 ,|()@. Requires strategy="ngram".

  • add_period (bool) –

    Indicates if we want the period of each date (time, part_of_day, day, week, month or year) returned in the tuple, before the detected language. time and part_of_day require the RETURN_TIME_AS_PERIOD setting.

    New in version 1.5.0.

Returns:

Returns list of tuples containing: substrings representing date and/or time, corresponding datetime.datetime object, 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:

list

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.timezone_parser module

class dateparser.timezone_parser.StaticTzInfo(name: str, offset: timedelta)[source]

Bases: tzinfo

dst(dt: datetime | None) → timedelta[source]

datetime -> DST offset as timedelta positive east of UTC.

localize(dt: datetime, is_dst: bool = False) → datetime[source]
tzname(dt: datetime | None) → str[source]

datetime -> string name of time zone.

utcoffset(dt: datetime | None) → timedelta[source]

datetime -> timedelta showing offset from UTC, negative values indicating West of UTC

dateparser.timezone_parser.convert_to_local_tz(datetime_obj: datetime, datetime_tz_offset: timedelta) → datetime[source]
dateparser.timezone_parser.get_local_tz_offset() → timedelta[source]
dateparser.timezone_parser.is_timezone_token(token: str) → bool[source]

Whether token is, 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 the ACT zone). 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.timezone_parser.word_is_tz(word: str) → bool[source]

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(date_time: datetime, tz_string: str) → datetime[source]
dateparser.utils.apply_timezone_from_settings(date_obj: datetime, settings: Settings | None) → datetime[source]
dateparser.utils.apply_tzdatabase_timezone(date_time: datetime, pytz_string: str) → datetime[source]
dateparser.utils.combine_dicts(primary_dict: Mapping[str, Any], supplementary_dict: Mapping[str, Any]) → OrderedDict[str, Any][source]
dateparser.utils.find_date_separator(format: str) → str | None[source]
dateparser.utils.get_last_day_of_month(year: int, month: int) → int[source]
dateparser.utils.get_logger() → Logger[source]
dateparser.utils.get_next_leap_year(year: int) → int[source]
dateparser.utils.get_previous_leap_year(year: int) → int[source]
dateparser.utils.get_timezone_from_tz_string(tz_string: str) → tzinfo[source]
dateparser.utils.localize_timezone(date_time: datetime, tz_string: str) → datetime[source]
dateparser.utils.normalize_unicode(string: str, form: Literal['NFC', 'NFD', 'NFKC', 'NFKD'] = 'NFKD') → str[source]
dateparser.utils.registry(cls: type[_T]) → type[_T][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.

dateparser.utils.set_correct_month_from_settings(date_obj: datetime, settings: Settings, current_month: int | None = None) → datetime[source]

Set correct month attending the PREFER_MONTH_OF_YEAR setting.

dateparser.utils.setup_logging() → None[source]
dateparser.utils.strip_braces(date_string: str) → str[source]

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 %z is kept, while a time zone name matched by %Z is 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 languages and locales are not provided.

Returns:

Returns datetime representing parsed date if successful, else returns None

Return type:

datetime.

Raises:

ValueError: Unknown Language, TypeError: Languages argument must be a list, SettingValidationError: A provided setting is not valid.