Debian Codegraph @

docs/settings.rst

raw
1 .. _settings:
2
3 Settings
4 ========
5
6 `dateparser`'s parsing behavior can be configured by supplying settings as a dictionary to `settings` argument in :func:`dateparser.parse` or :class:`DateDataParser <dateparser.date.DateDataParser>` constructor.
7
8 .. note:: From `dateparser 1.0.0` when a setting with a wrong value is provided, a ``SettingValidationError`` is raised.
9
10
11 All supported `settings` with their usage examples are given below:
12
13
14 Date Order
15 ++++++++++
16
17 ``DATE_ORDER``: specifies the order in which date components `year`, `month` and `day` are expected while parsing ambiguous dates. It defaults to ``MDY`` which translates to `month` first, `day` second and `year` last order. Characters `M`, `D` or `Y` can be shuffled to meet required order. For example, ``DMY`` specifies `day` first, `month` second and `year` last order:
18
19 >>> parse('15-12-18 06:00') # assumes default order: MDY
20 datetime.datetime(2018, 12, 15, 6, 0) # since 15 is not a valid value for Month, it is swapped with Day's
21 >>> parse('15-12-18 06:00', settings={'DATE_ORDER': 'YMD'})
22 datetime.datetime(2015, 12, 18, 6, 0)
23
24 ``PREFER_LOCALE_DATE_ORDER``: defaults to ``True``. Most languages have a default ``DATE_ORDER`` specified for them. For example, for French it is ``DMY``:
25
26 >>> # parsing ambiguous date
27 >>> parse('02-03-2016') # assumes english language, uses MDY date order
28 datetime.datetime(2016, 2, 3, 0, 0)
29 >>> parse('le 02-03-2016') # detects french, hence, uses DMY date order
30 datetime.datetime(2016, 3, 2, 0, 0)
31
32 .. note:: There's no language level default ``DATE_ORDER`` associated with `en` language. That's why it assumes ``MDY`` which is :obj:``settings <dateparser.conf.settings>`` default. If the language has a default ``DATE_ORDER`` associated, supplying custom date order will not be applied unless we set ``PREFER_LOCALE_DATE_ORDER`` to ``False``:
33
34 >>> parse('le 02-03-2016', settings={'DATE_ORDER': 'MDY'})
35 datetime.datetime(2016, 3, 2, 0, 0) # MDY didn't apply
36
37 >>> parse('le 02-03-2016', settings={'DATE_ORDER': 'MDY', 'PREFER_LOCALE_DATE_ORDER': False})
38 datetime.datetime(2016, 2, 3, 0, 0) # MDY worked!
39
40
41 Timezone Related Configurations
42 +++++++++++++++++++++++++++++++
43
44 ``TIMEZONE``: defaults to local timezone. When specified, resultant :class:`datetime <datetime.datetime>` is localized with the given timezone. Can be timezone abbreviation or any of `tz database name as given here <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones>`_.
45
46 >>> parse('January 12, 2012 10:00 PM', settings={'TIMEZONE': 'US/Eastern'})
47 datetime.datetime(2012, 1, 12, 22, 0)
48
49 ``TO_TIMEZONE``: defaults to None. When specified, resultant :class:`datetime <datetime.datetime>` converts according to the supplied timezone:
50
51 >>> settings = {'TIMEZONE': 'UTC', 'TO_TIMEZONE': 'US/Eastern'}
52 >>> parse('January 12, 2012 10:00 PM', settings=settings)
53 datetime.datetime(2012, 1, 12, 17, 0)
54
55 ``RETURN_AS_TIMEZONE_AWARE``: if ``True`` returns tz aware datetime objects in case timezone is detected in the date string.
56
57 >>> parse('30 mins ago', settings={'RETURN_AS_TIMEZONE_AWARE': True})
58 datetime.datetime(2017, 3, 13, 1, 43, 10, 243565, tzinfo=<DstTzInfo 'Asia/Karachi' PKT+5:00:00 STD>)
59
60 >>> parse('12 Feb 2015 10:56 PM EST', settings={'RETURN_AS_TIMEZONE_AWARE': False})
61 datetime.datetime(2015, 2, 12, 22, 56)
62
63
64 Handling Incomplete Dates
65 +++++++++++++++++++++++++
66
67 ``PREFER_DAY_OF_MONTH``: it comes handy when the date string is missing the day part. It defaults to ``current`` and can be ``first`` and ``last`` denoting first and last day of months respectively as values:
68
69 >>> from dateparser import parse
70 >>> parse('December 2015') # default behavior
71 datetime.datetime(2015, 12, 16, 0, 0)
72 >>> parse('December 2015', settings={'PREFER_DAY_OF_MONTH': 'last'})
73 datetime.datetime(2015, 12, 31, 0, 0)
74 >>> parse('December 2015', settings={'PREFER_DAY_OF_MONTH': 'first'})
75 datetime.datetime(2015, 12, 1, 0, 0)
76
77 ``PREFER_MONTH_OF_YEAR``: Similarly, another useful thing when the date string is missing the month part. It defaults to ``current`` and can be ``first`` and ``last`` denoting first and last month of year respectively as values:
78
79 >>> from dateparser import parse
80 >>> parse("2015") # default behavior
81 datetime.datetime(2015, 3, 27, 0, 0)
82 >>> parse("2015", settings={"PREFER_MONTH_OF_YEAR": "last"})
83 datetime.datetime(2015, 12, 27, 0, 0)
84 >>> parse("2015", settings={"PREFER_MONTH_OF_YEAR": "first"})
85 datetime.datetime(2015, 1, 27, 0, 0)
86 >>> parse("2015", settings={"PREFER_MONTH_OF_YEAR": "current"}) # it exactly behaves like default one
87 datetime.datetime(2015, 3, 27, 0, 0)
88
89 ``PREFER_DATES_FROM``: defaults to ``current_period`` and can have ``past`` and ``future`` as values.
90
91 If date string is missing some part, this option ensures consistent results depending on the ``past`` or ``future`` preference, for example, assuming current date is `June 16, 2015`:
92
93 >>> from dateparser import parse
94 >>> parse('March')
95 datetime.datetime(2015, 3, 16, 0, 0)
96 >>> parse('March', settings={'PREFER_DATES_FROM': 'future'})
97 datetime.datetime(2016, 3, 16, 0, 0)
98 >>> # parsing with preference set for 'past'
99 >>> parse('August', settings={'PREFER_DATES_FROM': 'past'})
100 datetime.datetime(2015, 8, 15, 0, 0)
101
102 ``RELATIVE_BASE``: allows setting the base datetime to use for interpreting partial or relative date strings.
103 Defaults to the current date and time.
104
105 For example, assuming current date is `June 16, 2015`:
106
107 >>> from dateparser import parse
108 >>> parse('14:30')
109 datetime.datetime(2015, 6, 16, 14, 30)
110 >>> parse('14:30', settings={'RELATIVE_BASE': datetime.datetime(2020, 1, 1)})
111 datetime.datetime(2020, 1, 1, 14, 30)
112 >>> parse('tomorrow', settings={'RELATIVE_BASE': datetime.datetime(2020, 1, 1)})
113 datetime.datetime(2020, 1, 2, 0, 0)
114
115 ``RETURN_TIME_SPAN``
116 ~~~~~~~~~~~~~~~~~~~~
117
118 **default**: ``False``
119
120 When enabled, `search_dates` detects time span expressions (e.g., "past month", "last week") and returns start/end dates instead of single dates.
121
122 ``DEFAULT_START_OF_WEEK``
123 ~~~~~~~~~~~~~~~~~~~~~~~~~
124
125 **default**: ``'monday'``
126
127 Sets which day starts the week for time span calculations. Options: ``'monday'``, ``'sunday'``.
128
129 ``DEFAULT_DAYS_IN_MONTH``
130 ~~~~~~~~~~~~~~~~~~~~~~~~~
131
132 **default**: ``30``
133
134 Sets the number of days to use for "past month" and similar expressions in time span detection.
135
136 ``STRICT_PARSING``: defaults to ``False``.
137
138 When set to ``True`` if missing any of ``day``, ``month`` or ``year`` parts, it does not return any result altogether.:
139
140 >>> parse('March', settings={'STRICT_PARSING': True})
141 None
142
143 ``REQUIRE_PARTS``: ensures results are dates that have all specified parts. It defaults to ``[]`` and can include ``day``, ``month`` and/or ``year``.
144
145 For example, assuming current date is `June 16, 2019`:
146
147 >>> parse('2012') # default behavior
148 datetime.datetime(2012, 6, 16, 0, 0)
149 >>> parse('2012', settings={'REQUIRE_PARTS': ['month']})
150 None
151 >>> parse('March 2012', settings={'REQUIRE_PARTS': ['day']})
152 None
153 >>> parse('March 12, 2012', settings={'REQUIRE_PARTS': ['day']})
154 datetime.datetime(2012, 3, 12, 0, 0)
155 >>> parse('March 12, 2012', settings={'REQUIRE_PARTS': ['day', 'month', 'year']})
156 datetime.datetime(2012, 3, 12, 0, 0)
157
158 ``IGNORE_SURROUNDING_TEXT``: defaults to ``False``. By default, the whole input string
159 must be a date, so a date wrapped in surrounding text is not parsed. When this setting
160 is enabled and the whole string could not be parsed as a date, dateparser retries
161 ignoring the words at the beginning and at the end of the string that the tried
162 language does not recognize as date-related:
163
164 >>> parse('Actualisé le 17 avril 2019', languages=['fr'])
165 None
166 >>> parse('Actualisé le 17 avril 2019', languages=['fr'], settings={'IGNORE_SURROUNDING_TEXT': True})
167 datetime.datetime(2019, 4, 17, 0, 0)
168 >>> parse('Published on 16/04/2019', settings={'IGNORE_SURROUNDING_TEXT': True})
169 datetime.datetime(2019, 4, 16, 0, 0)
170
171 Only the edges of the string are affected. An unrecognized word inside the date still
172 prevents parsing, and strings that can be parsed as a whole are parsed exactly as if
173 the setting was disabled:
174
175 >>> parse('17 foobar avril 2019', languages=['fr'], settings={'IGNORE_SURROUNDING_TEXT': True})
176 None
177
178 Stripping stops at the first token the language *does* recognize, and a number counts
179 as recognized. So surrounding text that contains a number of its own (an id, a page
180 number, a count) is not ignored, and the string is not parsed:
181
182 >>> parse('invoice 12345 paid on 3 March 2019', settings={'IGNORE_SURROUNDING_TEXT': True})
183 None
184
185 To extract a date out of arbitrary text that does not follow this shape, use
186 :func:`dateparser.search.search_dates` instead, which scans the whole string rather
187 than only trimming its edges.
188
189 .. warning:: When this setting is enabled, discarded edge text is dropped even if it
190 could have changed the meaning of the date, and what remains is parsed as if it
191 were the whole input. As a result, strings that merely contain date-like words can
192 produce a date, e.g. ``'Chapter 12 March of the Penguins'``. A recognized timezone is
193 kept and applied only when it is the last token of the string (e.g.
194 ``'... 1:21 PM EST'``); a timezone before the date, one followed by further
195 unrecognized text, or any timezone name the parser does not recognize, is discarded
196 with the rest of the surrounding text (use
197 :func:`dateparser.search.search_dates` for such input). Enable this setting only when
198 the input is expected to contain a date, and consider combining it with
199 ``STRICT_PARSING`` or ``REQUIRE_PARTS`` to discard remainders that are not complete
200 dates.
201
202
203 Language Detection
204 ++++++++++++++++++
205
206 ``SKIP_TOKENS``: it is a ``list`` of tokens to discard while detecting language. Defaults to ``['t']`` which skips T in iso format datetime string .e.g. ``2015-05-02T10:20:19+0000``.:
207
208 >>> from dateparser.date import DateDataParser
209 >>> DateDataParser(settings={'SKIP_TOKENS': ['de']}).get_date_data(u'27 Haziran 1981 de') # Turkish (at 27 June 1981)
210 DateData(date_obj=datetime.datetime(1981, 6, 27, 0, 0), period='day', locale='tr')
211
212 ``NORMALIZE``: applies unicode normalization (removing accents, diacritics...) when parsing the words. Defaults to True.
213
214 >>> dateparser.parse('4 decembre 2015', settings={'NORMALIZE': False})
215 # It doesn't work as the expected input should be '4 décembre 2015'
216
217 >>> dateparser.parse('4 decembre 2015', settings={'NORMALIZE': True})
218 datetime.datetime(2015, 12, 4, 0, 0)
219
220
221 Default Languages
222 +++++++++++++++++
223
224 ``DEFAULT_LANGUAGES``: It is a ``list`` of language codes in ISO 639 that will be used as default
225 languages for parsing when language detection fails. eg. ["en", "fr"]:
226
227 >>> from dateparser import parse
228 >>> parse('3 de marzo de 2020', settings={'DEFAULT_LANGUAGES': ["es"]})
229
230 .. note:: When using this setting, these languages will be tried after trying with the detected languages with no success. It is especially useful when using ``detect_languages_function``.
231
232 Language Order
233 ++++++++++++++
234
235 ``USE_GIVEN_LANGUAGE_ORDER``: defaults to ``False``. By default, the languages and
236 locales passed through the ``languages`` and ``locales`` arguments are tried in the
237 order of the most common languages, regardless of the order in which they are given.
238 Set this to ``True`` to instead try them in the order in which they are given, which
239 is useful when that order already reflects a preference (for example, the output of a
240 language detector ordered by confidence):
241
242 >>> import dateparser
243 >>> dateparser.parse('11/12/2020', languages=['es', 'en'])
244 datetime.datetime(2020, 11, 12, 0, 0)
245 >>> dateparser.parse('11/12/2020', languages=['es', 'en'], settings={'USE_GIVEN_LANGUAGE_ORDER': True})
246 datetime.datetime(2020, 12, 11, 0, 0)
247
248 It also applies to the languages given through the ``DEFAULT_LANGUAGES`` setting when
249 they are used as a fallback.
250
251 .. note:: This setting only reorders the languages and locales that are given. If
252 neither ``languages`` nor ``locales`` is provided, it has no effect and the default
253 order is used:
254
255 >>> dateparser.parse('11/12/2020', settings={'USE_GIVEN_LANGUAGE_ORDER': True})
256 datetime.datetime(2020, 11, 12, 0, 0)
257
258 .. note:: This setting does not affect :func:`dateparser.search.search_dates`, which
259 detects a single most likely language and normalizes the text before parsing, so it
260 does not use the given language order to disambiguate values such as ``11/12``.
261
262 Optional language detection
263 +++++++++++++++++++++++++++
264
265 ``LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD``: defaults to ``0.5``. It is a ``float`` of minimum required confidence for the custom language detection:
266
267 >>> from dateparser import parse
268 >>> parse('3 de marzo de 2020', settings={'LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD': 0.5}, detect_languages_function=detect_languages)
269
270
271 Other settings
272 ++++++++++++++
273
274 ``RETURN_TIME_AS_PERIOD``: returns ``time`` as period in date object, if time component is present in date string.
275 Defaults to ``False``.
276
277 >>> ddp = DateDataParser(settings={'RETURN_TIME_AS_PERIOD': True})
278 >>> ddp.get_date_data('vr jan 24, 2014 12:49')
279 DateData(date_obj=datetime.datetime(2014, 1, 24, 12, 49), period='time', locale='nl')
280
281 ``PARSERS``: it is a list of names of parsers to try, allowing to customize which
282 parsers are tried against the input date string, and in which order they are
283 tried.
284
285 The following parsers exist:
286
287 - ``'timestamp'``: If the input string starts with 10 digits, optionally
288 followed by additional digits or a period (``.``), those first 10 digits
289 are interpreted as `Unix time <https://en.wikipedia.org/wiki/Unix_time>`_.
290
291 - ``'negative-timestamp'``: ``'timestamp'`` for negative timestamps. For
292 example, parses ``-186454800000`` as ``1964-02-03T23:00:00``.
293
294 - ``'relative-time'``: Parses dates and times expressed in relation to the
295 current date and time (e.g. “1 day ago”, “in 2 weeks”).
296
297 - ``'custom-formats'``: Parses dates that match one of the date formats in
298 the list of the ``date_formats`` parameter of :func:`dateparser.parse` or
299 :meth:`DateDataParser.get_date_data
300 <dateparser.date.DateDataParser.get_date_data>`.
301
302 - ``'absolute-time'``: Parses dates and times expressed in absolute form
303 (e.g. “May 4th”, “1991-05-17”). It takes into account settings such as
304 ``DATE_ORDER`` or ``PREFER_LOCALE_DATE_ORDER``.
305
306 - ``'no-spaces-time'``: Parses dates and times that consist in only digits or
307 a combination of digits and non-digits where the first non-digit it's a colon
308 (e.g. “121994”, “11:052020”). It's not included in the default parsers and it
309 can produce false positives frequently.
310
311
312 :data:`dateparser.settings.default_parsers` contains the default value of
313 ``PARSERS`` (the list above, in that order) and can be used to write code that
314 changes the parsers to try without skipping parsers that may be added to
315 Dateparser in the future. For example, to ignore relative times:
316
317 >>> from dateparser_data.settings import default_parsers
318 >>> parsers = [parser for parser in default_parsers if parser != 'relative-time']
319 >>> parse('today', settings={'PARSERS': parsers})
320
321 ``CACHE_SIZE_LIMIT``: limits the size of caches, that store data for already processed dates.
322 Default to ``1000``, but you can set ``0`` for turning off the limit.