Debian Codegraph @

metomi/isodatetime/parsers.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # ----------------------------------------------------------------------------
3 # Copyright (C) British Crown (Met Office) & Contributors.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 # ----------------------------------------------------------------------------
18
19 """This provides ISO 8601 parsing functionality."""
20
21 import re
22 import sre_constants
23
24 from . import data
25 from . import parser_spec
26 from . import timezone
27 from metomi.isodatetime.exceptions import (
28 ISO8601SyntaxError, StrptimeConversionError)
29
30
31 class TimeRecurrenceParser(object):
32
33 """Parser for ISO 8601 recurrence expressions.
34
35 Keyword arguments:
36 timepoint_parser (default None) should be an instance of
37 TimePointParser, or None to use a normal TimePointParser instance.
38 duration_parser (default None) should be an instance of
39 DurationParser, or None to generate a normal
40 DurationParser.
41
42 Callable (via self.parse method) with an ISO 8601-compliant
43 recurrence pattern - this returns a TimeRecurrence instance.
44
45 """
46
47 RECURRENCE_REGEXES = [
48 re.compile(r"^R(?P<reps>\d+)?/(?P<start>[^P][^/]*)/(?P<end>[^P].*)$"),
49 re.compile(r"^R(?P<reps>\d+)?/(?P<start>[^P][^/]*)/(?P<intv>P.+)$"),
50 re.compile(r"^R(?P<reps>\d+)?/(?P<intv>P.+)/(?P<end>[^P].*)$")]
51
52 def __init__(self, timepoint_parser=None, duration_parser=None):
53 if timepoint_parser is None:
54 self.timepoint_parser = TimePointParser()
55 else:
56 self.timepoint_parser = timepoint_parser
57 if duration_parser is None:
58 self.duration_parser = DurationParser()
59 else:
60 self.duration_parser = duration_parser
61
62 def parse(self, expression):
63 """Parse a recurrence string into a TimeRecurrence instance."""
64 for regex in self.RECURRENCE_REGEXES:
65 result = regex.search(expression)
66 if not result:
67 continue
68 result_map = result.groupdict()
69 repetitions = None
70 start_point = None
71 end_point = None
72 duration = None
73 if "reps" in result_map and result_map["reps"] is not None:
74 repetitions = int(result_map["reps"])
75 if "start" in result_map:
76 start_point = self.timepoint_parser.parse(result_map["start"])
77 if "end" in result_map:
78 end_point = self.timepoint_parser.parse(result_map["end"])
79 if "intv" in result_map:
80 duration = self.duration_parser.parse(
81 result_map["intv"])
82 return data.TimeRecurrence(
83 repetitions=repetitions,
84 start_point=start_point,
85 end_point=end_point,
86 duration=duration
87 )
88 raise ISO8601SyntaxError("recurrence", expression)
89
90 __call__ = parse
91
92
93 class TimePointParser(object):
94
95 """Container for ISO 8601 date/time expressions.
96
97 Keyword arguments:
98 num_expanded_year_digits (default 2) specifies the extra year
99 digits allowed by the ISO standard - for example, 1995 can be
100 written as +001995 with 2 extra year digits.
101
102 allow_truncated (default False) specifies that ISO 8601:2000
103 truncations are allowed (not allowed in the ISO 8601:2004
104 standard which supersedes it).
105
106 allow_only_basic (default False) specifies that only the basic
107 forms of date and time in the ISO standard are allowed (no
108 extraneous punctuation). This means that "2000-01-02T01:14:02"
109 is not allowed, and must be written as "20000102T011402".
110
111 assumed_time_zone (default None) is a tuple of hours (integer)
112 and minutes (integer) that specifies that dates and times
113 without time zone information should be set to have a time zone
114 whose offset from UTC is the (hours, minutes) information in this
115 variable. To assume UTC, set this to (0, 0).
116
117 default_to_unknown_time_zone (default False) specifies that
118 dates and times without time zone information (in the absence of
119 assumed_time_zone) should be left with an unknown time zone
120 setting. Otherwise, the current local time zone will be used.
121
122 dump_format (default None) specifies a default custom dump format
123 string for TimePoint instances. See data.TimePoint documentation
124 for syntax.
125
126 """
127
128 def __init__(self, num_expanded_year_digits=2,
129 allow_truncated=False,
130 allow_only_basic=False,
131 assumed_time_zone=None,
132 default_to_unknown_time_zone=False,
133 dump_format=None):
134 self.num_expanded_year_digits = num_expanded_year_digits
135 self.allow_truncated = allow_truncated
136 self.allow_only_basic = allow_only_basic
137 self.assumed_time_zone = assumed_time_zone
138 self.default_to_unknown_time_zone = default_to_unknown_time_zone
139 self.dump_format = dump_format
140 self._generate_regexes()
141
142 def _generate_regexes(self):
143 """Generate combined date time strings."""
144 date_map = parser_spec.DATE_EXPRESSIONS
145 time_map = parser_spec.TIME_EXPRESSIONS
146 time_zone_map = parser_spec.TIME_ZONE_EXPRESSIONS
147 self._date_regex_map = {}
148 self._time_regex_map = {}
149 self._time_zone_regex_map = {}
150 format_ok_keys = ["basic", "extended"]
151 if self.allow_only_basic:
152 format_ok_keys = ["basic"]
153 for format_type in format_ok_keys:
154 self._date_regex_map.setdefault(format_type, {})
155 self._time_regex_map.setdefault(format_type, {})
156 self._time_zone_regex_map.setdefault(format_type, [])
157 for date_key in date_map[format_type].keys():
158 self._date_regex_map[format_type].setdefault(date_key, [])
159 regex_list = self._date_regex_map[format_type][date_key]
160 for date_expr in self.get_expressions(
161 date_map[format_type][date_key]):
162 date_regex = self.parse_date_expression_to_regex(
163 date_expr)
164 regex_list.append([re.compile(date_regex), date_expr])
165 for time_key in time_map[format_type].keys():
166 self._time_regex_map[format_type].setdefault(time_key, [])
167 regex_list = self._time_regex_map[format_type][time_key]
168 for time_expr in self.get_expressions(
169 time_map[format_type][time_key]):
170 time_regex = self.parse_time_expression_to_regex(
171 time_expr)
172 regex_list.append([re.compile(time_regex), time_expr])
173 for time_zone_expr in self.get_expressions(
174 time_zone_map[format_type]):
175 time_zone_regex = self.parse_time_zone_expression_to_regex(
176 time_zone_expr)
177 self._time_zone_regex_map[format_type].append(
178 [re.compile(time_zone_regex), time_zone_expr])
179
180 @staticmethod
181 def get_expressions(text):
182 """Yield valid expressions from text."""
183 for line in text.splitlines():
184 line_text = line.strip()
185 if not line_text or line_text.startswith("#"):
186 continue
187 expr_text = line_text.split("#", 1)[0].strip()
188 yield expr_text
189
190 def parse_date_expression_to_regex(self, expression):
191 """Construct regular expressions for the date."""
192 for expr_regex, substitute, _, _ in (
193 parser_spec.get_date_translate_info(
194 self.num_expanded_year_digits)):
195 expression = re.sub(expr_regex, substitute, expression)
196 expression = "^" + expression + "$"
197 return expression
198
199 @staticmethod
200 def parse_time_expression_to_regex(expression):
201 """Construct regular expressions for the time."""
202 for expr_regex, substitute, _, _ in (
203 parser_spec.get_time_translate_info()):
204 expression = re.sub(expr_regex, substitute, expression)
205 expression = "^" + expression + "$"
206 return expression
207
208 @staticmethod
209 def parse_time_zone_expression_to_regex(expression):
210 """Construct regular expressions for the time zone."""
211 for expr_regex, substitute, _, _ in (
212 parser_spec.get_time_zone_translate_info()):
213 expression = re.sub(expr_regex, substitute, expression)
214 expression = "^" + expression + "$"
215 return expression
216
217 def parse(self, timepoint_string, dump_format=None, dump_as_parsed=False,
218 is_duration=False):
219 """Parse a user-supplied timepoint string.
220
221 Args:
222 timepoint_string (str):
223 Timepoint string used to retrieve date and time properties
224 from.
225 dump_format (str, optional):
226 The format to be used to dump data.
227 dump_as_parsed (bool, optional):
228 If True the dump format used will be picked based on the
229 parsed expression.
230 is_duration (bool, optional):
231 If True the datetime will not be checked to make sure values
232 are within bounds, and if the values of month_of_year,
233 day_of_month etc are not supplied they will be assumed to be 0
234 instead of 1.
235
236 Returns:
237 TimePoint
238
239 """
240 date_info, time_info, parsed_expr = self.get_info(timepoint_string)
241 if dump_as_parsed:
242 dump_format = parsed_expr
243 time_point = self._create_timepoint_from_info(
244 date_info, time_info, is_duration=is_duration,
245 dump_format=dump_format, truncated_dump_format=dump_format)
246 return time_point
247
248 def _create_timepoint_from_info(self, date_info, time_info,
249 is_duration=False, dump_format=None,
250 truncated_dump_format=None):
251 info = {}
252 truncated_property = None
253 if date_info.get("truncated"):
254 if "year_of_decade" in date_info:
255 truncated_property = "year_of_decade"
256 if "year_of_century" in date_info:
257 truncated_property = "year_of_century"
258 elif ("century" not in date_info and
259 "year_of_century" in date_info):
260 truncated_property = "year_of_century"
261 date_info["truncated"] = True
262 is_year_present = True
263 if date_info.get("truncated"):
264 is_year_present = False
265 for property_ in ["year", "year_of_decade", "century",
266 "year_of_century", "expanded_year",
267 "year_sign"]:
268 if date_info.get(property_) is not None:
269 is_year_present = True
270 if is_year_present:
271 year = int(date_info.get("year", 0))
272 if "year_of_decade" in date_info:
273 year += int(date_info.pop("year_of_decade"))
274 truncated_property = "year_of_decade"
275 year += int(date_info.pop("year_of_century", 0))
276 year += 100 * int(date_info.pop("century", 0))
277 expanded_year = date_info.pop("expanded_year", 0)
278 if expanded_year:
279 date_info["num_expanded_year_digits"] = (
280 self.num_expanded_year_digits)
281 year += 10000 * int(expanded_year)
282 if date_info.pop("year_sign", "+") == "-":
283 year *= -1
284 date_info["year"] = year
285 for key, value in date_info.items():
286 try:
287 date_info[key] = int(value)
288 except (TypeError, ValueError):
289 pass
290 info.update(date_info)
291 for key, value in list(time_info.items()):
292 if key.endswith("_decimal"):
293 value = "0." + value
294 try:
295 value = float(value)
296 except (IOError, TypeError, ValueError):
297 pass
298 if key == "time_zone_utc" and value == "Z":
299 time_info.pop(key)
300 time_info.update({"time_zone_hour": 0,
301 "time_zone_minute": 0})
302 continue
303 time_info[key] = value
304 info.update(time_info)
305 if info.pop("truncated", False):
306 info["truncated"] = True
307 if truncated_property is not None:
308 info["truncated_property"] = truncated_property
309 if dump_format is None and self.dump_format:
310 dump_format = self.dump_format
311 if dump_format is not None:
312 info.update({"dump_format": dump_format})
313 if truncated_dump_format is not None:
314 info.update({"truncated_dump_format": truncated_dump_format})
315 return data.TimePoint(**info, is_duration=is_duration)
316
317 def strptime(self, strptime_data_string, strptime_format_string,
318 dump_format=None):
319 """Implement equivalent of Python's datetime.datetime.strptime.
320
321 Return an isodatetime.data.TimePoint representing
322 strptime_data_string based on the format given in
323 strptime_format_string.
324 dump_format is a custom dump format string (not in strftime
325 format).
326
327 """
328 split_format = parser_spec.REC_SPLIT_STRFTIME_DIRECTIVE.split(
329 strptime_format_string)
330 regex = "^"
331 for item in split_format:
332 if parser_spec.REC_STRFTIME_DIRECTIVE_TOKEN.search(item):
333 regex += parser_spec.translate_strptime_token(item)[0]
334 else:
335 regex += re.escape(item)
336 regex += "$"
337 return self._parse_from_custom_regex(
338 regex, strptime_data_string,
339 dump_format=dump_format, source=strptime_format_string)
340
341 def _parse_from_custom_regex(self, regex, data_string, dump_format=None,
342 source=None):
343 """Parse data_string according to the regular expression in regex."""
344 try:
345 compiled_regex = re.compile(regex)
346 except sre_constants.error:
347 raise StrptimeConversionError(source, regex)
348 result = compiled_regex.match(data_string)
349 if not result:
350 raise StrptimeConversionError(source, data_string)
351 info = result.groupdict()
352 for property_, value in list(info.items()):
353 if property_ in data.PARSE_PROPERTY_TRANSLATORS:
354 info.pop(property_)
355 translator = data.PARSE_PROPERTY_TRANSLATORS[property_]
356 info.update(translator(value))
357 date_info_keys = []
358 for item in parser_spec.get_date_translate_info(
359 self.num_expanded_year_digits):
360 date_info_keys.append(item[3])
361 time_info_keys = []
362 for item in parser_spec.get_time_translate_info():
363 time_info_keys.append(item[3])
364 date_info = {}
365 time_info = {}
366 time_zone_info = {}
367 for key, value in info.items():
368 if key in date_info_keys:
369 date_info[key] = value
370 elif key in time_info_keys:
371 time_info[key] = value
372 else:
373 time_zone_info[key] = value
374 time_zone_info = self.process_time_zone_info(time_zone_info)
375 time_info.update(time_zone_info)
376 return self._create_timepoint_from_info(
377 date_info, time_info, dump_format=dump_format)
378
379 def get_date_info(self, date_string, bad_types=None):
380 """Return the format and properties from a date string."""
381 type_keys = ["complete", "truncated", "reduced"]
382 if bad_types is not None:
383 for type_key in bad_types:
384 type_keys.remove(type_key)
385 if not self.allow_truncated and "truncated" in type_keys:
386 type_keys.remove("truncated")
387 for format_key, type_regex_map in self._date_regex_map.items():
388 for type_key in type_keys:
389 regex_list = type_regex_map[type_key]
390 for regex, expr in regex_list:
391 result = regex.match(date_string)
392 if result:
393 return ((format_key, type_key, expr),
394 result.groupdict())
395 raise ISO8601SyntaxError("date", date_string)
396
397 def get_time_info(self, time_string, bad_formats=None, bad_types=None):
398 """Return the properties from a time string."""
399 if bad_formats is None:
400 bad_formats = []
401 if bad_types is None:
402 bad_types = []
403 for format_key, type_regex_map in self._time_regex_map.items():
404 if format_key in bad_formats:
405 continue
406 for type_key, regex_list in type_regex_map.items():
407 if type_key in bad_types:
408 continue
409 for regex, expr in regex_list:
410 result = regex.match(time_string)
411 if result:
412 return expr, result.groupdict()
413 raise ISO8601SyntaxError("time", time_string)
414
415 def get_time_zone_info(self, time_zone_string, bad_formats=None):
416 """Return the properties from a time zone string."""
417 if bad_formats is None:
418 bad_formats = []
419 for format_key, regex_list in self._time_zone_regex_map.items():
420 if format_key in bad_formats:
421 continue
422 for regex, expr in regex_list:
423 result = regex.match(time_zone_string)
424 if result:
425 return expr, result.groupdict()
426 raise ISO8601SyntaxError("time zone", time_zone_string)
427
428 def get_info(self, timepoint_string):
429 """Return the date and time properties from a timepoint string."""
430 date_time_time_zone = timepoint_string.split(
431 parser_spec.TIME_DESIGNATOR)
432 parsed_expr = ""
433 if len(date_time_time_zone) == 1:
434 date = date_time_time_zone[0]
435 keys, date_info = self.get_date_info(date)
436 format_key, type_key, date_expr = keys
437 parsed_expr += date_expr
438 time_info = {}
439 time_zone_info = (
440 self.process_time_zone_info({}))
441 time_info.update(time_zone_info)
442 else:
443 date, time_time_zone = date_time_time_zone
444 if not date and self.allow_truncated:
445 keys = (None, "truncated", "")
446 date_info = {"truncated": True}
447 else:
448 keys, date_info = self.get_date_info(date,
449 bad_types=["reduced"])
450 format_key, type_key, date_expr = keys
451 parsed_expr += date_expr
452 bad_formats = []
453 if format_key == "basic":
454 bad_formats = ["extended"]
455 if format_key == "extended":
456 bad_formats = ["basic"]
457 if type_key == "truncated":
458 # Do not force basic/extended formatting for truncated dates.
459 bad_formats = []
460 bad_types = ["truncated"]
461 if date_info.get("truncated"):
462 bad_types = []
463 if time_time_zone.endswith("Z"):
464 time, time_zone = time_time_zone[:-1], "Z"
465 elif "+" in time_time_zone:
466 time, time_zone = time_time_zone.split("+")
467 time_zone = "+" + time_zone
468 elif "-" in time_time_zone:
469 time, time_zone = time_time_zone.rsplit("-", 1)
470 time_zone = "-" + time_zone
471 # Make sure this isn't just a truncated time.
472 try:
473 time_expr, time_info = self.get_time_info(
474 time,
475 bad_formats=bad_formats,
476 bad_types=bad_types
477 )
478 time_zone_expr, time_zone_info = self.get_time_zone_info(
479 time_zone,
480 bad_formats=bad_formats
481 )
482 except ISO8601SyntaxError:
483 time = time_time_zone
484 time_zone = None
485 else:
486 time = time_time_zone
487 time_zone = None
488 if time_zone is None:
489 time_zone_info = {}
490 time_zone_expr = ""
491 time_zone_info = (
492 self.process_time_zone_info(time_zone_info))
493 else:
494 time_zone_expr, time_zone_info = self.get_time_zone_info(
495 time_zone,
496 bad_formats=bad_formats
497 )
498 time_zone_info = self.process_time_zone_info(time_zone_info)
499 time_expr, time_info = self.get_time_info(
500 time, bad_formats=bad_formats, bad_types=bad_types)
501 parsed_expr += parser_spec.TIME_DESIGNATOR + (
502 time_expr + time_zone_expr)
503 time_info.update(time_zone_info)
504 return date_info, time_info, parsed_expr
505
506 def process_time_zone_info(self, time_zone_info=None):
507 """Rationalise time zone data and set defaults if appropriate."""
508 if time_zone_info is None:
509 time_zone_info = {}
510 if not time_zone_info:
511 # There is no time zone information specified.
512 if self.assumed_time_zone is None:
513 # No given value to assume.
514 if self.default_to_unknown_time_zone:
515 # Return no time zone information.
516 return {}
517 # Set the time zone to the current local time zone.
518 utc_hour_offset, utc_minute_offset = (
519 timezone.get_local_time_zone())
520 time_zone_info["time_zone_hour"] = utc_hour_offset
521 time_zone_info["time_zone_minute"] = utc_minute_offset
522 return time_zone_info
523 else:
524 # Set the time zone to a given value.
525 utc_hour_offset, utc_minute_offset = self.assumed_time_zone
526 time_zone_info["time_zone_hour"] = utc_hour_offset
527 time_zone_info["time_zone_minute"] = utc_minute_offset
528 return time_zone_info
529 if time_zone_info.pop("time_zone_sign", "+") == "-":
530 time_zone_info["time_zone_hour"] = (
531 -int(time_zone_info["time_zone_hour"]))
532 if "time_zone_minute" in time_zone_info:
533 time_zone_info["time_zone_minute"] = (
534 -int(time_zone_info["time_zone_minute"]))
535 return time_zone_info
536
537
538 class DurationParser(object):
539
540 """Parser for ISO 8601 Durations (durations)."""
541
542 DURATION_REGEXES = [
543 re.compile(r"""^P(?:(?P<years>\d+)Y)?
544 (?:(?P<months>\d+)M)?
545 (?:(?P<days>\d+)D)?$""", re.X),
546 re.compile(r"""^P(?:(?P<years>\d+)Y)?
547 (?:(?P<months>\d+)M)?
548 (?:(?P<days>\d+)D)?
549 T(?:(?P<hours>\d.*)H)?
550 (?:(?P<minutes>\d.*)M)?
551 (?:(?P<seconds>\d.*)S)?$""", re.X),
552 re.compile(r"""^P(?P<weeks>\d+)W$""", re.X)
553 ]
554
555 def parse(self, expression):
556 """Parse an ISO duration expression into a Duration instance."""
557 sign_factor = 1
558 if expression.startswith("-"):
559 sign_factor = -1
560 expression = expression[1:]
561 for rec_regex in self.DURATION_REGEXES:
562 result = rec_regex.search(expression)
563 if not result:
564 continue
565 result_map = result.groupdict()
566 for key, value in list(result_map.items()):
567 if value is None:
568 result_map.pop(key)
569 continue
570 if key in ["years", "months", "days", "weeks"]:
571 value = int(value)
572 else:
573 if "," in value:
574 value = value.replace(",", ".")
575 value = float(value)
576 result_map[key] = value * sign_factor
577 return data.Duration(**result_map)
578 if expression.startswith("P") and sign_factor != -1:
579 # TimePoint-like duration - don't allow our negative extension.
580 try:
581 timepoint = parse_timepoint_expression(
582 expression[1:],
583 # this is a duration but we are parsing it as a timepoint
584 is_duration=True,
585 allow_truncated=False,
586 assumed_time_zone=(0, 0)
587 )
588 except ISO8601SyntaxError:
589 raise ISO8601SyntaxError("duration", expression)
590 if timepoint.get_is_week_date():
591 raise ISO8601SyntaxError("duration", expression)
592 result_map = {}
593 result_map["years"] = timepoint._year
594 if timepoint.get_is_calendar_date():
595 result_map["months"] = timepoint._month_of_year
596 result_map["days"] = timepoint._day_of_month
597 if timepoint.get_is_ordinal_date():
598 result_map["days"] = timepoint._day_of_year
599 result_map["hours"] = timepoint._hour_of_day
600 if timepoint._minute_of_hour is not None:
601 result_map["minutes"] = timepoint._minute_of_hour
602 if timepoint._second_of_minute is not None:
603 result_map["seconds"] = timepoint._second_of_minute
604 return data.Duration(**result_map)
605 raise ISO8601SyntaxError("duration", expression)
606
607
608 def parse_timepoint_expression(timepoint_expression, is_duration=False,
609 **kwargs):
610 """Return a data model that represents timepoint_expression."""
611 parser = TimePointParser(**kwargs)
612 return parser.parse(timepoint_expression, is_duration=is_duration)