Debian Codegraph @

metomi/isodatetime/data.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 data model functionality."""
20
21
22 from . import dumpers
23 from . import timezone
24 from .exceptions import BadInputError
25
26 import operator
27 from functools import lru_cache
28 from math import floor
29
30
31 _operator_map = {op.__name__: op for op in [
32 operator.eq, operator.lt, operator.le, operator.gt, operator.ge]}
33
34
35 class Calendar:
36
37 """Store constants for Gregorian calendar date-time calculation."""
38
39 SECONDS_IN_MINUTE = 60
40 MINUTES_IN_HOUR = 60
41 HOURS_IN_DAY = 24
42 DAYS_IN_WEEK = 7
43 DAYS_IN_MONTHS = None # This is set up in the set_* methods.
44 DAYS_IN_MONTHS_LEAP = None # This is set up in the set_* methods
45 ROUGH_DAYS_IN_MONTH = 30 # Used for duration conversion, nowhere else.
46 MAX_WEEKS_IN_YEAR = 53 # In ISO week year, used for truncated dates
47
48 LEAP_YEAR_FACTOR_TRUTHS = [(4, True), (100, False), (400, True)]
49
50 MODE_360 = "360day"
51 MODE_360_DAY = "360_day"
52 MODE_365 = "365day"
53 MODE_365_DAY = "365_day"
54 MODE_366 = "366day"
55 MODE_366_DAY = "366_day"
56 MODE_GREGORIAN = "gregorian"
57 DAYS_IN_MONTHS_360 = 12 * (30,)
58 DAYS_IN_MONTHS_365 = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
59 DAYS_IN_MONTHS_366 = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
60
61 # {mode: (days_in_months, days_in_months_leap), ...}
62 MODES = {
63 MODE_360: (DAYS_IN_MONTHS_360, None),
64 MODE_360_DAY: (DAYS_IN_MONTHS_360, None),
65 MODE_365: (DAYS_IN_MONTHS_365, None),
66 MODE_365_DAY: (DAYS_IN_MONTHS_365, None),
67 MODE_366: (DAYS_IN_MONTHS_366, None),
68 MODE_366_DAY: (DAYS_IN_MONTHS_366, None),
69 MODE_GREGORIAN: (DAYS_IN_MONTHS_365, DAYS_IN_MONTHS_366),
70 }
71
72 WEEK_DAY_START_REFERENCE = {"calendar": (2000, 1, 3),
73 "ordinal": (2000, 3)}
74 UNIX_EPOCH_DATE_TIME_REFERENCE_PROPERTIES = {
75 "year": 1970, "time_zone_hour": 0, "time_zone_minute": 0}
76
77 _DEFAULT = None
78
79 @classmethod
80 def default(cls):
81 """Return the singleton instance. Create if necessary."""
82 if cls._DEFAULT is None:
83 cls._DEFAULT = cls()
84 return cls._DEFAULT
85
86 def __init__(self):
87 self.set_mode()
88
89 def set_mode(self, mode=None):
90 """Set calendar mode.
91
92 mode -- calendar mode, which can be one of the keys in Calendar.MODES.
93 If None, default to MODE_GREGORIAN.
94
95 """
96 if not mode:
97 mode = self.MODE_GREGORIAN
98 days_in_months, days_in_months_leap = self.MODES[mode.lower()]
99 if days_in_months_leap is None:
100 days_in_months_leap = days_in_months
101 self.DAYS_IN_MONTHS = days_in_months
102 self.DAYS_IN_MONTHS_LEAP = days_in_months_leap
103 self.mode = mode
104
105 # Recalculate
106 self.SECONDS_IN_HOUR = self.SECONDS_IN_MINUTE * self.MINUTES_IN_HOUR
107 self.SECONDS_IN_DAY = self.SECONDS_IN_HOUR * self.HOURS_IN_DAY
108 self.MINUTES_IN_DAY = self.MINUTES_IN_HOUR * self.HOURS_IN_DAY
109 self.INDEXED_DAYS_IN_MONTHS = [
110 (i + 1, days) for i, days in enumerate(self.DAYS_IN_MONTHS)]
111 self.INDEXED_DAYS_IN_MONTHS_LEAP = [
112 (i + 1, days) for i, days in enumerate(self.DAYS_IN_MONTHS_LEAP)]
113 self.REVERSED_INDEXED_DAYS_IN_MONTHS = (
114 reversed(self.INDEXED_DAYS_IN_MONTHS))
115 self.REVERSED_INDEXED_DAYS_IN_MONTHS_LEAP = (
116 reversed(self.INDEXED_DAYS_IN_MONTHS))
117 self.MONTHS_IN_YEAR = len(self.DAYS_IN_MONTHS)
118 # No support for MONTHS_IN_YEAR_LEAP (some calendars...)
119 self.DAYS_IN_YEAR = sum(self.DAYS_IN_MONTHS)
120 self.ROUGH_DAYS_IN_YEAR = self.DAYS_IN_YEAR
121 self.DAYS_IN_YEAR_LEAP = sum(self.DAYS_IN_MONTHS_LEAP)
122 self.MAX_DAYS_IN_MONTH = max(self.DAYS_IN_MONTHS)
123 self.HOURS_IN_YEAR = self.DAYS_IN_YEAR * self.HOURS_IN_DAY
124 self.MINUTES_IN_YEAR = self.DAYS_IN_YEAR * self.MINUTES_IN_DAY
125 self.SECONDS_IN_YEAR = self.DAYS_IN_YEAR * self.SECONDS_IN_DAY
126 self.HOURS_IN_YEAR_LEAP = self.DAYS_IN_YEAR_LEAP * self.HOURS_IN_DAY
127 self.MINUTES_IN_YEAR_LEAP = (
128 self.DAYS_IN_YEAR_LEAP * self.MINUTES_IN_DAY)
129 self.SECONDS_IN_YEAR_LEAP = (
130 self.DAYS_IN_YEAR_LEAP * self.SECONDS_IN_DAY)
131
132 def __repr__(self):
133 return "<{0}.{1}: {2}>".format(
134 self.__module__, self.__class__.__name__, self.mode)
135
136
137 CALENDAR = Calendar.default()
138
139
140 TIMEPOINT_DUMPER_MAP = {
141 0: dumpers.TimePointDumper(num_expanded_year_digits=0),
142 2: dumpers.TimePointDumper(num_expanded_year_digits=2)
143 }
144
145
146 class TimeRecurrence:
147
148 """Represent a recurring duration.
149
150 There are four possible formats for recurrences in ISO 8601:
151 1. Recur with a duration given by the difference between a start date-time
152 and a subsequent date-time.
153 2. (Not supported) Recur with a specified duration, starting at some
154 context date-time specified elsewhere.
155 3. Recur with a specified duration starting at a particular date-time.
156 4. Recur with a specified duration ending at a particular date-time (the
157 starting date-time is calculated from the duration).
158
159 The format of the TimeRecurrence instance is automatically chosen from the
160 arguments supplied.
161
162 Keyword arguments:
163
164 repetitions (int): The number of repetitions in the recurrence. If set
165 to 1, the recurrence simply consists of one date-time, with no
166 duration (i.e., the number of repetitions is inclusive of the first
167 occurrence). If omitted, the number of repetitions is unbounded.
168 start_point (TimePoint): Start date-time of the recurrence.
169 duration (Duration): The duration of each repetition interval in the
170 recurrence.
171 end_point (TimePoint): End date-time of the recurrence (format 4), or if
172 using format 1, the end date-time of the first interval.
173 min_point (TimePoint): If specified, marks the start of a subset of 'valid'
174 date-times in the recurrence.
175 max_point (TimePoint): If specified, marks the end of a subset of 'valid'
176 date-times in the recurrence.
177 """
178
179 __slots__ = ["_repetitions", "_start_point", "_duration", "_end_point",
180 "_second_point", "_format_number", "_min_point", "_max_point"]
181
182 def __init__(self, repetitions=None, start_point=None,
183 duration=None, end_point=None, min_point=None,
184 max_point=None):
185 inputs = (
186 (repetitions, "repetitions", None, int),
187 (start_point, "start_point", None, TimePoint),
188 (duration, "duration", None, Duration),
189 (end_point, "end_point", None, TimePoint),
190 (min_point, "min_point", None, TimePoint),
191 (max_point, "max_point", None, TimePoint)
192 )
193 _type_checker(*inputs)
194 self._repetitions = repetitions
195 self._start_point = start_point
196 self._duration = duration
197 self._end_point = end_point
198 self._min_point = min_point
199 self._max_point = max_point
200 self._format_number = None
201 if self._repetitions is not None and self._repetitions <= 0:
202 raise BadInputError(BadInputError.RECURRENCE,
203 "Number of repetitions cannot be <= 0")
204 if self._duration is not None and self._duration < Duration(years=0):
205 raise BadInputError(BadInputError.RECURRENCE,
206 "Duration cannot be < P0Y")
207 if self._duration is None:
208 # First form.
209 self._format_number = 1
210 # One repetition means the event only occurs on the start date
211 if self._repetitions == 1:
212 self._second_point = self._end_point = self._start_point
213 return
214 if self._start_point is None or self._end_point is None:
215 raise BadInputError(
216 BadInputError.RECURRENCE, [i[:2] for i in inputs])
217 if self._start_point == self._end_point:
218 self._repetitions = 1
219 self._second_point = self._end_point
220 return
221 if self._end_point < self._start_point:
222 raise BadInputError(
223 BadInputError.RECURRENCE, "Start point {0} cannot be "
224 "earlier than end point of first interval {1}"
225 .format(self._start_point, self._end_point))
226 self._second_point = self._end_point
227 self._duration = self._second_point - self._start_point
228 if self._repetitions is None:
229 self._end_point = None
230 else:
231 self._end_point = (
232 self._start_point +
233 self._duration * (self._repetitions - 1))
234 elif self._end_point is None and self._start_point is not None:
235 # Third form.
236 self._format_number = 3
237 if self._repetitions == 1 or self._duration == Duration(years=0):
238 self._end_point = self._start_point
239 self._repetitions = 1
240 self._duration = None
241 elif self._repetitions is not None:
242 self._end_point = (
243 self._start_point +
244 self._duration * (self._repetitions - 1))
245 elif self._start_point is None and self._end_point is not None:
246 # Fourth form.
247 self._format_number = 4
248 if self._repetitions == 1 or self._duration == Duration(years=0):
249 self._start_point = self._end_point
250 self._repetitions = 1
251 self._duration = None
252 elif self._repetitions is not None:
253 self._start_point = (
254 self._end_point - self._duration * (self._repetitions - 1))
255 else:
256 raise BadInputError(
257 BadInputError.RECURRENCE, [i[:2] for i in inputs])
258
259 @property
260 def repetitions(self): return self._repetitions
261
262 @property
263 def start_point(self): return self._start_point
264
265 @property
266 def duration(self): return self._duration
267
268 @property
269 def end_point(self): return self._end_point
270
271 @property
272 def min_point(self): return self._min_point
273
274 @property
275 def max_point(self): return self._max_point
276
277 @property
278 def format_number(self): return self._format_number
279
280 def get_is_valid(self, timepoint: "TimePoint") -> bool:
281 """Return whether the timepoint is valid for this recurrence."""
282 if not self._get_is_in_bounds(timepoint):
283 return False
284 for iter_timepoint in self.__iter__():
285 if iter_timepoint == timepoint:
286 return True
287 if self._start_point is None and iter_timepoint < timepoint:
288 return False
289 if self._end_point is None and iter_timepoint > timepoint:
290 return False
291 return False
292
293 def get_next(self, timepoint: "TimePoint") -> "TimePoint":
294 """Return the next timepoint after this timepoint in the recurrence
295 series, or None."""
296 if self._repetitions == 1 or timepoint is None:
297 return None
298 next_timepoint = timepoint + self._duration
299 if self._get_is_in_bounds(next_timepoint):
300 return next_timepoint
301 return None
302
303 def get_prev(self, timepoint: "TimePoint") -> "TimePoint":
304 """Return the previous timepoint before this timepoint in the
305 recurrence series, or None."""
306 if self._repetitions == 1 or timepoint is None:
307 return None
308 prev_timepoint = timepoint - self._duration
309 if self._get_is_in_bounds(prev_timepoint):
310 return prev_timepoint
311 return None
312
313 def get_first_after(self, timepoint):
314 """Return the next timepoint in the series after the given timepoint
315 which is not necessarily part of the series.
316
317 If the given timepoint is before the start point, return the
318 start point, or if it is after the end point, return None.
319 """
320 if self._get_is_in_bounds(timepoint):
321 if self._duration is not None and self._duration.is_exact():
322 # Since it's exact, we can do maths instead of iterating
323 iterations, seconds_since = divmod(
324 (timepoint - self._start_point).get_seconds(),
325 self._duration.get_seconds())
326 return timepoint + (self._duration - Duration(
327 seconds=floor(seconds_since)))
328 else:
329 # Since duration is inexact, we have to iterate
330 current = self._start_point
331 while current is not None and current <= timepoint:
332 current = self.get_next(current)
333 return current
334 elif timepoint < self._start_point:
335 return self._start_point
336 return None
337
338 def __getitem__(self, index: int) -> "TimePoint":
339 if index < 0 or not isinstance(index, int):
340 raise IndexError("Unsupported index for TimeRecurrence")
341 for i, point in enumerate(self.__iter__()):
342 if index == i:
343 return point
344 raise IndexError("Invalid index for TimeRecurrence")
345
346 def _get_is_in_bounds(self, timepoint: "TimePoint") -> bool:
347 """Return whether the timepoint is within this recurrence series."""
348 if timepoint is None:
349 return False
350 if self._start_point is not None and timepoint < self._start_point:
351 return False
352 if self._min_point is not None and timepoint < self._min_point:
353 return False
354 if self._max_point is not None and timepoint > self._max_point:
355 return False
356 if self._end_point is not None and timepoint > self._end_point:
357 return False
358 return True
359
360 def __iter__(self):
361 if self._start_point is None:
362 point = self._end_point
363 in_reverse = True
364 else:
365 point = self._start_point
366 in_reverse = False
367
368 if self._repetitions == 1 or not self._duration:
369 if self._get_is_in_bounds(point):
370 yield point
371 point = None
372
373 while point is not None:
374 if self._get_is_in_bounds(point):
375 yield point
376 else:
377 break
378 if in_reverse:
379 point = self.get_prev(point)
380 else:
381 point = self.get_next(point)
382
383 def __hash__(self) -> int:
384 return hash((self._repetitions, self._start_point, self._end_point,
385 self._duration, self._min_point, self._max_point))
386
387 def __eq__(self, other: "TimeRecurrence") -> bool:
388 if not isinstance(other, TimeRecurrence):
389 return NotImplemented
390 for attr in ["_repetitions", "_start_point", "_end_point", "_duration",
391 "_min_point", "_max_point"]:
392 if getattr(self, attr) != getattr(other, attr):
393 return False
394 return True
395
396 def __add__(self, other: "Duration") -> "TimeRecurrence":
397 if not isinstance(other, Duration):
398 raise TypeError(
399 "Invalid type for addition: '{0}' should be Duration."
400 .format(type(other).__name__)
401 )
402 if self._format_number == 1:
403 kwargs = {"start_point": self._start_point + other,
404 "end_point": self._second_point + other}
405 elif self._format_number == 3:
406 kwargs = {"start_point": self._start_point + other,
407 "duration": self._duration}
408 elif self._format_number == 4:
409 kwargs = {"end_point": self._end_point + other,
410 "duration": self._duration}
411 return self.__class__(
412 repetitions=self._repetitions, **kwargs,
413 min_point=self._min_point, max_point=self._max_point)
414
415 def __sub__(self, other: "Duration") -> "TimeRecurrence":
416 return self + -1 * other
417
418 def __str__(self):
419 if self._repetitions is None:
420 prefix = "R/"
421 else:
422 prefix = "R" + str(self._repetitions) + "/"
423 duration_str = (
424 str(self._duration) if self._duration is not None else 'P0Y')
425 if self._format_number == 1:
426 return (prefix + str(self._start_point) + "/" +
427 str(self._second_point))
428 elif self._format_number == 3:
429 return prefix + str(self._start_point) + "/" + duration_str
430 elif self._format_number == 4:
431 return prefix + duration_str + "/" + str(self._end_point)
432 return "R/?/?"
433
434 def __repr__(self):
435 return "<{0}.{1}: {2}>".format(
436 self.__module__, self.__class__.__name__, str(self))
437
438
439 class Duration:
440
441 """Represent a duration or period of time.
442
443 Note that years and months are 'nominal' durations, whose exact length of
444 time depends on their position in the calendar. E.g., a duration of
445 1 calendar year starts on a particular day of a particular month and ends
446 on the same day of the same month in the following calendar year, and may
447 be different to 365 days in the Gregorian calendar due to leap years.
448
449 For this reason, be careful when using the comparison operators. For the
450 sake of `<`, `<=`, `>` and `>=`, the behaviour is: P1Y = P365D and
451 P1M = P30D. However, these are not NOT true for the equality operator
452 (`==`).
453
454 Conversely, weeks, days, hours, minutes and seconds are exact units, so
455 P1W == P7D, P1D == PT24H and PT1H == PT60M etc. are always true. (Although
456 ISO 8601 states that weeks and days are nominal durations, there is no case
457 where they are not exact in our implementation.)
458
459 Keyword arguments:
460
461 years (int): number of calendar years in the duration (an inexact unit
462 due to the possibility of leap years).
463 months (int) number of calendar months in the duration (also an inexact
464 unit due to the differing number of calendar days in the calendar
465 months).
466 weeks (int): number of calendar weeks in the duration - cannot be used in
467 conjunction with other units (use multiples of 7 days instead).
468 days (int): number of calendar days in the duration.
469 hours (float): number of hours in the duration.
470 minutes (float): number of minutes in the duration.
471 seconds (float): number of seconds in the duration.
472 standardize (bool): if True, switches on adjusting the attributes so that
473 small units have minimal values. For example, 3664.4 seconds would
474 become 1 hour, 1 minute, and 4.4 seconds. Attributes will not adjust
475 for units that are inexact (months and years).
476 _is_empty_instance (bool): If True, do not set any properties yet. These
477 should be set as part of a copy operation.
478 """
479
480 __slots__ = ["_years", "_months", "_weeks", "_days",
481 "_hours", "_minutes", "_seconds"]
482
483 def __init__(self, years=0, months=0, weeks=0, days=0,
484 hours=0.0, minutes=0.0, seconds=0.0, standardize=False,
485 _is_empty_instance=False):
486 if _is_empty_instance:
487 return
488 _type_checker(
489 (years, "years", int, None),
490 (months, "months", int, None),
491 (weeks, "weeks", int, None),
492 (days, "days", int, None),
493 (hours, "hours", int, float, None),
494 (minutes, "minutes", int, float, None),
495 (seconds, "seconds", int, float, None)
496 )
497 self._years = years
498 self._months = months
499 self._weeks = None
500 self._days = days
501 if weeks is not None:
502 if days is None:
503 self._days = CALENDAR.DAYS_IN_WEEK * weeks
504 else:
505 self._days += CALENDAR.DAYS_IN_WEEK * weeks
506 self._hours = hours
507 self._minutes = minutes
508 self._seconds = seconds
509 if (weeks and not years and not months and not days and
510 not hours and not minutes and not seconds):
511 self._weeks = self._days // CALENDAR.DAYS_IN_WEEK
512 self._years, self._months, self._days = (None, None, None)
513 self._hours, self._minutes, self._seconds = (None, None, None)
514 if standardize:
515 if self._seconds:
516 num_minutes, self._seconds = divmod(
517 self._seconds, CALENDAR.SECONDS_IN_MINUTE)
518 if self._minutes is None:
519 self._minutes = 0
520 self._minutes += num_minutes
521 if self._minutes:
522 num_hours, self._minutes = divmod(
523 self._minutes, CALENDAR.MINUTES_IN_HOUR)
524 if self._hours is None:
525 self._hours = 0
526 self._hours += num_hours
527 if self._hours:
528 num_days, self._hours = divmod(
529 self._hours, CALENDAR.HOURS_IN_DAY)
530 if self._days is None:
531 self._days = 0
532 self._days += num_days
533
534 @property
535 def years(self): return self._years
536
537 @property
538 def months(self): return self._months
539
540 @property
541 def weeks(self): return self._weeks
542
543 @property
544 def days(self): return self._days
545
546 @property
547 def hours(self): return self._hours
548
549 @property
550 def minutes(self): return self._minutes
551
552 @property
553 def seconds(self): return self._seconds
554
555 def _copy(self):
556 """Return an (unlinked) copy of this instance."""
557 new = self.__class__(_is_empty_instance=True)
558 for attr in self.__slots__:
559 setattr(new, attr, getattr(self, attr))
560 return new
561
562 def is_exact(self):
563 """Return True if the instance is defined in non-nominal/exact units
564 (weeks, days, hours, minutes or seconds) only."""
565 if self._years or self._months:
566 return False
567 return True
568
569 def get_days_and_seconds(self):
570 """Return a roughly-converted duration in days and seconds.
571
572 This cannot be accurate for non-uniform units such as years and
573 months, and may yield incorrect results if used for comparisons
574 derived from durations using these units.
575
576 Seconds are returned in the range
577 0 <= seconds < CALENDAR.SECONDS_IN_DAY, which means that a
578 Duration which has self.seconds = CALENDAR.SECONDS_IN_DAY +
579 100 will return 1 day, 100 seconds or (1, 100) from this
580 method.
581 """
582 if self.get_is_in_weeks():
583 return self._weeks * CALENDAR.DAYS_IN_WEEK, 0
584 # TODO: Implement error calculation for the below quantities.
585 new_days = (self._years * CALENDAR.ROUGH_DAYS_IN_YEAR +
586 self._months * CALENDAR.ROUGH_DAYS_IN_MONTH +
587 self._days)
588 new_seconds = (self._hours * CALENDAR.SECONDS_IN_HOUR +
589 self._minutes * CALENDAR.SECONDS_IN_MINUTE +
590 self._seconds)
591 diff_days, new_seconds = divmod(new_seconds, CALENDAR.SECONDS_IN_DAY)
592 new_days += diff_days
593 return new_days, new_seconds
594
595 def get_seconds(self):
596 """Return a roughly-converted duration in seconds.
597
598 This is not rigorous when converting from non-uniform units
599 such as years and months.
600 """
601 if self.is_exact():
602 return self._get_non_nominal_seconds()
603 days, seconds = self.get_days_and_seconds()
604 return days * CALENDAR.SECONDS_IN_DAY + seconds
605
606 def _get_non_nominal_seconds(self):
607 """Return the length of time (in seconds) represented by the exact
608 units (weeks, days, hours, minutes and seconds) only, ignoring
609 years and months."""
610 if self.get_is_in_weeks():
611 return (self._weeks * CALENDAR.DAYS_IN_WEEK *
612 CALENDAR.SECONDS_IN_DAY)
613 return (self._days * CALENDAR.SECONDS_IN_DAY +
614 self._hours * CALENDAR.SECONDS_IN_HOUR +
615 self._minutes * CALENDAR.SECONDS_IN_MINUTE + self._seconds)
616
617 def get_is_in_weeks(self):
618 """Return whether we are in week representation."""
619 return self._weeks is not None
620
621 def to_days(self):
622 """Return a new Duration in day representation rather than weeks."""
623 if self.get_is_in_weeks():
624 new = self._copy()
625 for attribute in ["_years", "_months", "_hours",
626 "_minutes", "_seconds"]:
627 if getattr(new, attribute) is None:
628 setattr(new, attribute, 0)
629 new._days = new._weeks * CALENDAR.DAYS_IN_WEEK
630 new._weeks = None
631 return new
632 return self
633
634 def to_weeks(self):
635 """Return a new Duration in week representation (use with caution -
636 this returns the floor of the decimal number of weeks, so might lose
637 precision)."""
638 if not self.get_is_in_weeks():
639 weeks = self._days // CALENDAR.DAYS_IN_WEEK
640 return Duration(weeks=weeks)
641 return self
642
643 def __abs__(self):
644 new = self._copy()
645 for attribute in new.__slots__:
646 attr_value = getattr(new, attribute)
647 if attr_value is not None:
648 setattr(new, attribute, abs(attr_value))
649 return new
650
651 def __add__(self, other):
652 new = self._copy()
653 if isinstance(other, Duration):
654 if new.get_is_in_weeks():
655 if other.get_is_in_weeks():
656 new._weeks += other._weeks
657 return new
658 new = new.to_days()
659 elif other.get_is_in_weeks():
660 other = other.to_days()
661 new._years += other._years
662 new._months += other._months
663 new._days += other._days
664 new._hours += other._hours
665 new._minutes += other._minutes
666 new._seconds += other._seconds
667 return new
668 if isinstance(other, TimePoint) or isinstance(other, TimeRecurrence):
669 return other + new
670 raise TypeError(
671 "Invalid type for addition: " +
672 "'%s' should be Duration or TimePoint." %
673 type(other).__name__
674 )
675
676 def __sub__(self, other):
677 return self + -1 * other
678
679 def __mul__(self, other):
680 # TODO: support float multiplication?
681 if not isinstance(other, int):
682 raise TypeError(
683 "Invalid type for multiplication: " +
684 "'%s' should be integer." %
685 type(other).__name__
686 )
687 new = self._copy()
688 for attr in new.__slots__:
689 value = getattr(new, attr)
690 if value is not None:
691 setattr(new, attr, value * other)
692 return new
693
694 def __rmul__(self, other):
695 return self.__mul__(other)
696
697 def __floordiv__(self, other):
698 # TODO: support float division?
699 if not isinstance(other, int):
700 raise TypeError(
701 "Invalid type for division: " +
702 "'%s' should be integer." %
703 type(other).__name__
704 )
705 new = self._copy()
706 if self.get_is_in_weeks():
707 new._weeks //= other
708 return new
709 new._years //= other
710 new._months //= other
711 new._days //= other
712 new._hours //= other
713 new._minutes //= other
714 new._seconds //= other
715 return new
716
717 def __hash__(self) -> int:
718 # TODO: alt calendar modes
719 if self.get_is_in_weeks():
720 return hash((0, 0, self._get_non_nominal_seconds()))
721 return hash(
722 (self._years, self._months, self._get_non_nominal_seconds()))
723
724 def __eq__(self, other: "Duration") -> bool:
725 if isinstance(other, Duration):
726 if self.is_exact():
727 if other.is_exact():
728 return (self._get_non_nominal_seconds() ==
729 other._get_non_nominal_seconds())
730 return False
731 return (
732 self._years == other._years and
733 self._months == other._months and
734 self._get_non_nominal_seconds() ==
735 other._get_non_nominal_seconds()
736 )
737 return NotImplemented
738
739 def __lt__(self, other: "Duration") -> bool:
740 if isinstance(other, Duration):
741 return self.get_days_and_seconds() < other.get_days_and_seconds()
742 return NotImplemented
743
744 def __le__(self, other: "Duration") -> bool:
745 if isinstance(other, Duration):
746 return self.get_days_and_seconds() <= other.get_days_and_seconds()
747 return NotImplemented
748
749 def __gt__(self, other: "Duration") -> bool:
750 if isinstance(other, Duration):
751 return self.get_days_and_seconds() > other.get_days_and_seconds()
752 return NotImplemented
753
754 def __ge__(self, other: "Duration") -> bool:
755 if isinstance(other, Duration):
756 return self.get_days_and_seconds() >= other.get_days_and_seconds()
757 return NotImplemented
758
759 def __bool__(self):
760 for attr in self.__slots__:
761 if getattr(self, attr, None):
762 return True
763 return False
764
765 def __str__(self):
766 if not self:
767 return "P0Y"
768
769 start_string = "P"
770 content_string = ""
771
772 # Handle negative durations.
773 is_fully_negative = False
774 for attribute in self.__slots__:
775 attr_value = getattr(self, attribute)
776 if attr_value is not None:
777 if attr_value > 0:
778 is_fully_negative = False
779 break
780 if attr_value < 0:
781 is_fully_negative = True
782 if is_fully_negative:
783 # Support negative durations as extensions to the standard.
784 return "-" + str(abs(self))
785
786 # Weeks are not combined with any other unit.
787 if self.get_is_in_weeks():
788 return (start_string + str(self._weeks) + "W").replace(".", ",")
789
790 for prop_, unit in [("years", "Y"), ("months", "M"), ("days", "D"),
791 ("hours", "H"), ("minutes", "M"),
792 ("seconds", "S")]:
793 prop_val = getattr(self, prop_)
794 if prop_val:
795 if int(prop_val) == prop_val:
796 content_string += str(int(prop_val)) + unit
797 else:
798 content_string += str(prop_val) + unit
799 if prop_ == "days":
800 content_string += "T"
801
802 if content_string.endswith("T"):
803 # No time unit information, so strip the delimiter.
804 content_string = content_string[:-1]
805
806 total_string = start_string + content_string
807 return total_string.replace(".", ",")
808
809 def __repr__(self):
810 return "<{0}.{1}: {2}>".format(
811 self.__module__, self.__class__.__name__, str(self))
812
813
814 class TimeZone(Duration):
815
816 """Represent a time zone offset from UTC.
817
818 Keyword arguments:
819
820 hours (int): The hour component of the offset from UTC. May be positive,
821 zero, or negative, as required.
822 minutes (int): The minute component offset from UTC. If the UTC offset is
823 negative, this should be negative if non-zero.
824 unknown (bool): If True, the returned instance represents an unknown
825 TimeZone. Some operations and comparisons may fail when this is True.
826 _is_empty_instance (bool): If True, do not set any properties yet. These
827 should be set as part of a copy operation.
828 """
829
830 __slots__ = [*Duration.__slots__, "_unknown"]
831
832 to_weeks = property(doc='Unavailable/not inherited')
833
834 def __init__(self, hours=0, minutes=0, unknown=False,
835 _is_empty_instance=False):
836 if _is_empty_instance:
837 return
838 if hours is None:
839 hours = 0
840 else:
841 hours = _int_caster(hours, "TimeZone hours")
842 _bounds_checker(hours, "TimeZone hours",
843 min_val=-99, max_val=99)
844 if minutes is None:
845 minutes = 0
846 else:
847 minutes = _int_caster(minutes, "TimeZone minutes")
848 min_minutes = 1 - CALENDAR.MINUTES_IN_HOUR
849 max_minutes = CALENDAR.MINUTES_IN_HOUR - 1
850 if hours > 0:
851 min_minutes = 0
852 elif hours < 0:
853 max_minutes = 0
854 _bounds_checker(minutes, "TimeZone minutes",
855 min_val=min_minutes, max_val=max_minutes)
856 self._unknown = unknown
857 self._hours = hours
858 self._minutes = minutes
859 for attr in ["_years", "_months", "_days", "_seconds"]:
860 setattr(self, attr, 0)
861 self._weeks = None
862
863 @property
864 def unknown(self): return self._unknown
865
866 def __hash__(self) -> int:
867 # TODO: Do we have to worry about the possibility of a hash collision
868 # between instances of two different classes?
869 return hash((self._unknown, self._hours, self._minutes))
870
871 def __str__(self):
872 if self._unknown:
873 return ""
874 if self._hours == 0 and self._minutes == 0:
875 return "Z"
876 else:
877 time_string = "+%02d:%02d"
878 if self._hours < 0 or (self._hours == 0 and self._minutes < 0):
879 time_string = "-%02d:%02d"
880 return time_string % (abs(self._hours), abs(self._minutes))
881
882
883 class TimePoint:
884
885 """Represent an instant in time.
886
887 An ISO 8601 date/time instant can be represented in three separate ways:
888 - Calendar date: calendar year, calendar month, calendar day of the month
889 - Ordinal date: calendar year, calendar day of the year
890 - Week date: calendar (week) year, calendar week, calendar day of the week
891 (note: week years are not identical to calendar years).
892
893 This class maintains a date/time instant in the original
894 representation with which it was invoked - so it may be in any of
895 these formats. See the TimePoint.to_*_date methods for internal
896 conversions between formats.
897
898 Where properties are not given (consistent with ISO 8601 reduced
899 precision dates), they will be given the expected defaults if
900 truncation is not specified. For example, if only the year and the
901 month_of_year is given, the day_of_month will be set to 1.
902
903 Time zone information defaults to UTC. It is essential to provide it
904 unless you are happy with this behaviour. A date/time
905 representation is ambiguous without it.
906
907 Keyword arguments (usually default to None if not provided):
908
909 num_expanded_year_digits (default 0) - an agreed-upon number of extra
910 digits to represent the year, beyond the normal 4. For example,
911 a value of 2 would suggest representing the year 2000 as 002000.
912 year (int): A positive or negative integer. Note that ISO 8601 implies
913 using non-zero num_expanded_year_digits when using negative integers.
914 Remember we are using the proleptic Gregorian calendar, with a year
915 zero which does not exist in standard 1 BC => 1 AD usage - so 2 BC
916 should be represented as -1.
917 month_of_year (int): An integer between 1 and 12 inclusive, if using the
918 calendar date representation.
919 week_of_year (int): An integer between 1 and 52/53 (depending on the
920 year), if using the week date representation.
921 day_of_year (int): An integer between 1 and 365/366 (depending on the
922 year), if using the ordinal date representation.
923 day_of_month (int): An integer between 1 and 28/29/30/31 (depending on
924 the month and year), if using the calendar date representation.
925 day_of_week (int): An integer between 1 and 7, if using the week date
926 representation.
927 hour_of_day (int): An integer between 0 and 24 (note: 24 represents
928 midnight at the end of the day, which is equivalent to 00/midnight
929 the next day. If 24 is given, minute_of_hour must be 0).
930 hour_of_day_decimal (float): A float between 0 and 1, if using decimal
931 accuracy for hours. Note that you should not provide lower units
932 such as minute_of_hour or second_of_minute when using this.
933 minute_of_hour (int): An integer between 0 and 59.
934 minute_of_hour_decimal (float): A float between 0 and 1, if using decimal
935 accuracy for minutes. Note that you should not provide lower units
936 such as second_of_minute when using this.
937 second_of_minute (int): An integer between 0 and 59 (note: no support
938 for leap seconds yet).
939 second_of_minute_decimal (float): A float between 0 and 1, if using decimal
940 accuracy for seconds.
941 time_zone_hour (int): The hour component of the time zone offset from UTC,
942 between -99 and 99. The default is 0 unless this is a truncated
943 TimePoint.
944 time_zone_minute (int): The minute component of the time zone offset from
945 UTC. If the hour component is negative, this should be negative too.
946 dump_format (str): A custom format string to control the stringification
947 of the timepoint. See isodatetime.parser_spec for more details.
948 truncated (bool): Whether the date-time instant has purposefully incomplete
949 information (ISO 8601:2000 truncation). Default is False.
950 truncated_dump_format (str): A custom format to control the stringification
951 of the timepoint if it is truncated. See isodatetime.parser_spec for
952 more details.
953 truncated_property (str): Can either be "year_of_decade" or
954 "year_of_century". This is used for truncated representations to
955 distinguish between the two ways of truncating the year.
956 is_empty_instance (bool): If True, do not set any properties yet. These
957 should be set as part of a copy operation. Default is False.
958 is_duration (bool): For datetime-like durations syntax. If True the
959 args will not be checked to make sure values are within bounds, and if
960 the values of month_of_year, day_of_month etc are not supplied they
961 will be assumed to be 0 instead of 1. Default is False.
962 """
963
964 __slots__ = [
965 "_num_expanded_year_digits", "_year", "_month_of_year",
966 "_day_of_year", "_day_of_month", "_day_of_week",
967 "_week_of_year", "_hour_of_day", "_minute_of_hour",
968 "_second_of_minute", "_truncated", "_truncated_property",
969 "_truncated_dump_format", "_dump_format", "_time_zone"
970 ]
971
972 def __init__(self, num_expanded_year_digits=0, year=None,
973 month_of_year=None, week_of_year=None, day_of_year=None,
974 day_of_month=None, day_of_week=None,
975 hour_of_day=None, hour_of_day_decimal=None,
976 minute_of_hour=None, minute_of_hour_decimal=None,
977 second_of_minute=None, second_of_minute_decimal=None,
978 time_zone_hour=None, time_zone_minute=None,
979 dump_format=None, truncated=False,
980 truncated_dump_format=None, truncated_property=None,
981 is_empty_instance=False, is_duration=False):
982 if is_empty_instance:
983 # This has been created for a copy - set properties later.
984 return
985 if dump_format is not None and not isinstance(dump_format, str):
986 raise BadInputError(
987 BadInputError.TYPE,
988 "dump_format", repr(dump_format), type(dump_format))
989 if (truncated_dump_format is not None and
990 not isinstance(truncated_dump_format, str)):
991 raise BadInputError(
992 BadInputError.TYPE,
993 "truncated_dump_format", repr(truncated_dump_format),
994 type(truncated_dump_format)
995 )
996 if (truncated_property is not None and
997 truncated_property not in ["year_of_decade",
998 "year_of_century"]):
999 raise BadInputError(
1000 BadInputError.VALUES, "truncated_property",
1001 repr(truncated_property),
1002 "'year_of_decade' or 'year_of_century'")
1003 _type_checker(
1004 (num_expanded_year_digits, "num_expanded_year_digits", int),
1005 (year, "year", None, int),
1006 (month_of_year, "month_of_year", None, int),
1007 (week_of_year, "week_of_year", None, int),
1008 (day_of_year, "day_of_year", None, int),
1009 (day_of_month, "day_of_month", None, int),
1010 (day_of_week, "day_of_week", None, int),
1011 (hour_of_day, "hour_of_day", None, int, float),
1012 (hour_of_day_decimal, "hour_of_day_decimal", None, int, float),
1013 (minute_of_hour, "minute_of_hour", None, int, float),
1014 (minute_of_hour_decimal, "minute_of_hour_decimal", None, int,
1015 float),
1016 (second_of_minute, "second_of_minute", None, int, float),
1017 (second_of_minute_decimal, "second_of_minute_decimal", None, int,
1018 float)
1019 )
1020 self._dump_format = dump_format
1021 self._num_expanded_year_digits = _int_caster(
1022 num_expanded_year_digits, "num_expanded_year_digits")
1023 self._truncated = truncated
1024 self._truncated_dump_format = truncated_dump_format
1025 self._truncated_property = truncated_property
1026
1027 self._year = _int_caster(year, "year", allow_none=True)
1028 self._month_of_year = _int_caster(month_of_year, "year",
1029 allow_none=True)
1030 self._day_of_year = _int_caster(day_of_year, "day_of_year",
1031 allow_none=True)
1032 self._day_of_month = _int_caster(day_of_month, "day_of_month",
1033 allow_none=True)
1034 self._day_of_week = _int_caster(day_of_week, "day_of_week",
1035 allow_none=True)
1036 self._week_of_year = _int_caster(week_of_year, "week_of_year",
1037 allow_none=True)
1038 self._hour_of_day = _int_caster(hour_of_day, "hour_of_day",
1039 allow_none=True)
1040 if hour_of_day_decimal is not None:
1041 if self._hour_of_day is None:
1042 raise BadInputError(
1043 BadInputError.MISSING, "hour_of_day_decimal",
1044 "hour_of_day")
1045 hour_of_day_decimal = float(hour_of_day_decimal)
1046 _bounds_checker(hour_of_day_decimal, "hour_of_day_decimal",
1047 min_val=0, upper_val=1)
1048 self._hour_of_day += hour_of_day_decimal
1049 if minute_of_hour is not None:
1050 raise BadInputError(
1051 BadInputError.CONFLICT, "minute_of_hour",
1052 "hour_of_day_decimal")
1053 if second_of_minute is not None:
1054 raise BadInputError(
1055 BadInputError.CONFLICT, "second_of_minute",
1056 "hour_of_day_decimal")
1057 if minute_of_hour_decimal is not None:
1058 if minute_of_hour is None:
1059 raise BadInputError(
1060 BadInputError.MISSING, "minute_of_hour_decimal",
1061 "minute_of_hour")
1062 self._minute_of_hour = _int_caster(
1063 minute_of_hour, "minute_of_hour")
1064 minute_of_hour_decimal = float(minute_of_hour_decimal)
1065 _bounds_checker(minute_of_hour_decimal, "minute_of_hour_decimal",
1066 min_val=0, upper_val=1)
1067 self._minute_of_hour += minute_of_hour_decimal
1068 if second_of_minute is not None:
1069 raise BadInputError(
1070 BadInputError.CONFLICT, "second_of_minute",
1071 "minute_of_hour_decimal")
1072 else:
1073 self._minute_of_hour = _int_caster(
1074 minute_of_hour, "minute_of_hour", allow_none=True)
1075 if second_of_minute_decimal is not None:
1076 if second_of_minute is None:
1077 raise BadInputError(
1078 BadInputError.MISSING,
1079 "second_of_minute_decimal",
1080 "second_of_minute")
1081 self._second_of_minute = _int_caster(second_of_minute,
1082 "second_of_minute")
1083 second_of_minute_decimal = float(second_of_minute_decimal)
1084 _bounds_checker(second_of_minute_decimal,
1085 "second_of_minute_decimal", min_val=0, upper_val=1)
1086 self._second_of_minute += second_of_minute_decimal
1087 else:
1088 self._second_of_minute = _int_caster(
1089 second_of_minute, "second_of_minute", allow_none=True)
1090 if not self._truncated:
1091 if self._year is None:
1092 raise BadInputError("Missing input: year")
1093 if self._hour_of_day is None:
1094 self._hour_of_day = 0
1095 if hour_of_day_decimal is None and self._minute_of_hour is None:
1096 self._minute_of_hour = 0
1097 if (hour_of_day_decimal is None and
1098 minute_of_hour_decimal is None and
1099 self._second_of_minute is None):
1100 self._second_of_minute = 0
1101
1102 has_unknown_tz = self._truncated and not (
1103 time_zone_hour is not None or time_zone_minute is not None)
1104 self._time_zone = TimeZone(hours=time_zone_hour,
1105 minutes=time_zone_minute,
1106 unknown=has_unknown_tz)
1107
1108 month_is_specified = bool(self._month_of_year or self._day_of_month)
1109 week_is_specified = bool(self._week_of_year or self._day_of_week)
1110 if month_is_specified and week_is_specified:
1111 raise BadInputError(BadInputError.CONFLICT,
1112 "[week_of_year or day_of_week]",
1113 "[month_of_year or day_of_month]")
1114 if month_is_specified and self._day_of_year is not None:
1115 raise BadInputError(BadInputError.CONFLICT,
1116 "day_of_year",
1117 "[month_of_year or day_of_month]")
1118 if week_is_specified and self._day_of_year is not None:
1119 raise BadInputError(BadInputError.CONFLICT,
1120 "day_of_year",
1121 "[week_of_year or day_of_week]")
1122 if not is_duration:
1123 if not self._truncated and self._day_of_year is None:
1124 if not week_is_specified:
1125 if self._month_of_year is None:
1126 self._month_of_year = 1
1127 if self._day_of_month is None:
1128 self._day_of_month = 1
1129 else:
1130 if self._week_of_year is None:
1131 self._week_of_year = 1
1132 if self._day_of_week is None:
1133 self._day_of_week = 1
1134 self._check_bounds()
1135
1136 @property
1137 def num_expanded_year_digits(self): return self._num_expanded_year_digits
1138
1139 @property
1140 def year(self): return self._year
1141
1142 @property
1143 def month_of_year(self):
1144 if self._month_of_year is None:
1145 return self.get_calendar_date()[1]
1146 return self._month_of_year
1147
1148 @property
1149 def week_of_year(self):
1150 if self._week_of_year is None:
1151 return self.get_week_date()[1]
1152 return self._week_of_year
1153
1154 @property
1155 def day_of_year(self):
1156 if self._day_of_year is None:
1157 return self.get_ordinal_date()[1]
1158 return self._day_of_year
1159
1160 @property
1161 def day_of_month(self):
1162 if self._day_of_month is None:
1163 return self.get_calendar_date()[2]
1164 return self._day_of_month
1165
1166 @property
1167 def day_of_week(self):
1168 if self._day_of_week is None:
1169 return self.get_week_date()[2]
1170 return self._day_of_week
1171
1172 @property
1173 def hour_of_day(self): return self._hour_of_day
1174
1175 @property
1176 def minute_of_hour(self):
1177 if self._minute_of_hour is None:
1178 return self.get_hour_minute_second()[1]
1179 return self._minute_of_hour
1180
1181 @property
1182 def second_of_minute(self):
1183 if self._second_of_minute is None:
1184 return self.get_hour_minute_second()[2]
1185 return self._second_of_minute
1186
1187 @property
1188 def time_zone(self): return self._time_zone
1189 # NOTE: returns linked instance of TimeZone, but it shouldn't matter
1190 # because TimeZone is immutable
1191
1192 @property
1193 def truncated(self): return self._truncated
1194
1195 @property
1196 def truncated_property(self): return self._truncated_property
1197
1198 @property
1199 def truncated_dump_format(self): return self._truncated_dump_format
1200
1201 @property
1202 def dump_format(self): return self._dump_format
1203
1204 def get_is_calendar_date(self):
1205 """Return whether this is in years, month-of-year, day-of-month."""
1206 return self._month_of_year is not None
1207
1208 def get_is_ordinal_date(self):
1209 """Return whether this is in years, day-of-the year format."""
1210 return self._day_of_year is not None
1211
1212 def get_is_week_date(self):
1213 """Return whether this is in years, week-of-year, day-of-week."""
1214 return self._week_of_year is not None
1215
1216 def get_calendar_date(self):
1217 """Return the year, month-of-year and day-of-month for this date."""
1218 if self.get_is_calendar_date():
1219 return self._year, self._month_of_year, self._day_of_month
1220 if self.get_is_ordinal_date():
1221 return get_calendar_date_from_ordinal_date(self._year,
1222 self._day_of_year)
1223 if self.get_is_week_date():
1224 return get_calendar_date_from_week_date(self._year,
1225 self._week_of_year,
1226 self._day_of_week)
1227
1228 def get_hour_minute_second(self):
1229 """Return the time of day expressed in hours, minutes, seconds."""
1230 hour_of_day = self._hour_of_day
1231 minute_of_hour = self._minute_of_hour
1232 second_of_minute = self._second_of_minute
1233 if second_of_minute is None:
1234 if minute_of_hour is None:
1235 hour_decimals = hour_of_day - int(hour_of_day)
1236 hour_of_day = float(int(hour_of_day))
1237 minute_of_hour = CALENDAR.MINUTES_IN_HOUR * hour_decimals
1238 minute_decimals = minute_of_hour - int(minute_of_hour)
1239 minute_of_hour = float(int(minute_of_hour))
1240 second_of_minute = CALENDAR.SECONDS_IN_MINUTE * minute_decimals
1241 return hour_of_day, minute_of_hour, second_of_minute
1242
1243 def get_ordinal_date(self):
1244 """Return the year, day-of-year for this date."""
1245 if self.get_is_calendar_date():
1246 return get_ordinal_date_from_calendar_date(self._year,
1247 self._month_of_year,
1248 self._day_of_month)
1249 if self.get_is_ordinal_date():
1250 return self._year, self._day_of_year
1251 if self.get_is_week_date():
1252 return get_ordinal_date_from_week_date(self._year,
1253 self._week_of_year,
1254 self._day_of_week)
1255
1256 @property
1257 def year_sign(self): return "+" if self._year >= 0 else "-"
1258
1259 @property
1260 def expanded_year_digits(self):
1261 """The extra digits at the front of the expanded year, as opposed to
1262 the number of such digits"""
1263 return abs(self._year / 10000)
1264
1265 @property
1266 def century(self): return (abs(self._year) % 10000) // 100
1267
1268 @property
1269 def year_of_century(self): return abs(self._year) % 100
1270
1271 @property
1272 def year_of_decade(self): return abs(self._year) % 10
1273
1274 @property
1275 def decade_of_century(self):
1276 return (abs(self._year) % 100 - abs(self._year) % 10) // 10
1277
1278 @property
1279 def hour_of_day_decimal_string(self):
1280 return self._decimal_string("hour_of_day")
1281
1282 @property
1283 def minute_of_hour_decimal_string(self):
1284 return self._decimal_string("minute_of_hour")
1285
1286 @property
1287 def second_of_minute_decimal_string(self):
1288 return self._decimal_string("second_of_minute")
1289
1290 @property
1291 def time_zone_minute_abs(self): return abs(self._time_zone._minutes)
1292
1293 @property
1294 def time_zone_hour_abs(self): return abs(self._time_zone._hours)
1295
1296 @property
1297 def time_zone_sign(self):
1298 if self._time_zone._hours < 0 or self._time_zone._minutes < 0:
1299 return "-"
1300 return "+"
1301
1302 @property
1303 def seconds_since_unix_epoch(self):
1304 reference_timepoint = TimePoint(
1305 **CALENDAR.UNIX_EPOCH_DATE_TIME_REFERENCE_PROPERTIES)
1306 days, seconds = (self - reference_timepoint).get_days_and_seconds()
1307 # N.B. This needs altering if we implement leap seconds.
1308 return str(int(CALENDAR.SECONDS_IN_DAY * days + seconds))
1309
1310 def get(self, property_name):
1311 """Obsolete method for returning calculated value for property name."""
1312 raise NotImplementedError(
1313 "The method TimePoint.get('{0}') is obsolete; use TimePoint.{0} "
1314 "or getattr() instead".format(property_name))
1315 # return getattr(self, property_name)
1316
1317 def _decimal_string(self, attr):
1318 """Return the decimal digits (after the decimal point) of the specified
1319 attribute as a string. Rounds to 6 d.p."""
1320 decimal = float(getattr(self, attr)) - int(getattr(self, attr))
1321 if decimal >= 0.9999995:
1322 # Truncate instead of rounding up because ticking over the higher
1323 # quantities would be complicated
1324 return "999999"
1325 string = "%0.6f" % decimal
1326 string = string.split(".", 1)[1].rstrip("0")
1327 if not string:
1328 return "0"
1329 return string
1330
1331 def get_second_of_day(self):
1332 """Return the seconds elapsed since the start of the day."""
1333 second_of_day = 0
1334 if self._second_of_minute is not None:
1335 second_of_day += self._second_of_minute
1336 if self._minute_of_hour is not None:
1337 second_of_day += self._minute_of_hour * CALENDAR.SECONDS_IN_MINUTE
1338 second_of_day += self._hour_of_day * CALENDAR.SECONDS_IN_HOUR
1339 return second_of_day
1340
1341 def get_time_zone_utc(self) -> bool:
1342 # FIXME: Misleading name
1343 """Return whether the time zone is explicitly in UTC."""
1344 if self._time_zone._unknown:
1345 return False
1346 return self._time_zone._hours == 0 and self._time_zone._minutes == 0
1347
1348 def get_week_date(self):
1349 """Return the year, week-of-year, day-of-week for this date."""
1350 if self.get_is_calendar_date():
1351 return get_week_date_from_calendar_date(self._year,
1352 self._month_of_year,
1353 self._day_of_month)
1354 if self.get_is_ordinal_date():
1355 return get_week_date_from_ordinal_date(self._year,
1356 self._day_of_year)
1357 if self.get_is_week_date():
1358 return self._year, self._week_of_year, self._day_of_week
1359
1360 def get_time_zone_offset(self, other: "TimePoint") -> "Duration":
1361 """Get the difference in hours and minutes between time zones.
1362
1363 Args:
1364 other (TimePoint): The TimePoint to get the offset with respect to.
1365 """
1366 # TODO: unit test?
1367 if other._time_zone._unknown or self._time_zone._unknown:
1368 return Duration()
1369 return other._time_zone - self._time_zone
1370
1371 def to_time_zone(self, dest_time_zone: "TimeZone") -> "TimePoint":
1372 """Return a copy of this TimePoint in the specified time zone.
1373
1374 Args:
1375 dest_time_zone (TimeZone): The new time zone (a TimeZone instance).
1376 """
1377 if dest_time_zone._unknown:
1378 return self
1379 new = self + (dest_time_zone - self._time_zone)
1380 new._time_zone = dest_time_zone
1381 return new
1382
1383 def to_local_time_zone(self) -> "TimePoint":
1384 """Return a copy of this TimePoint in the local time zone."""
1385 local_hours, local_minutes = timezone.get_local_time_zone()
1386 return self.to_time_zone(
1387 TimeZone(hours=local_hours, minutes=local_minutes))
1388
1389 def to_utc(self) -> "TimePoint":
1390 """Return a copy of this TimePoint in the UTC time zone."""
1391 return self.to_time_zone(TimeZone(hours=0, minutes=0))
1392
1393 def to_calendar_date(self) -> "TimePoint":
1394 """Return a copy of this TimePoint reformatted in years, month-of-year
1395 and day-of-month."""
1396 if self.get_is_calendar_date():
1397 return self
1398 new = self._copy()
1399 new._year, new._month_of_year, new._day_of_month = (
1400 self.get_calendar_date())
1401 new._day_of_year = None
1402 new._week_of_year, new._day_of_week = (None, None)
1403 return new
1404
1405 def to_hour_minute_second(self) -> "TimePoint":
1406 """Return a copy of this TimePoint with any time fractions expanded
1407 into hours, minutes and seconds."""
1408 new = self._copy()
1409 new._hour_of_day, new._minute_of_hour, new._second_of_minute = (
1410 self.get_hour_minute_second())
1411 return new
1412
1413 def to_week_date(self) -> "TimePoint":
1414 """Return a copy of this TimePoint reformatted in years, week-of-year
1415 and day-of-week."""
1416 if self.get_is_week_date():
1417 return self
1418 new = self._copy()
1419 new._year, new._week_of_year, new._day_of_week = self.get_week_date()
1420 new._day_of_year = None
1421 new._month_of_year, new._day_of_month = (None, None)
1422 return new
1423
1424 def to_ordinal_date(self) -> "TimePoint":
1425 """Return a copy of this TimePoint reformatted in years and
1426 day-of-the-year."""
1427 new = self._copy()
1428 new._year, new._day_of_year = self.get_ordinal_date()
1429 new._month_of_year, new._day_of_month = (None, None)
1430 new._week_of_year, new._day_of_week = (None, None)
1431 return new
1432
1433 def get_largest_truncated_property_name(self):
1434 """Return the largest unit in a truncated representation."""
1435 if not self._truncated:
1436 return None
1437 prop_dict = self.get_truncated_properties()
1438 for attr in ["year_of_century", "year_of_decade", "month_of_year",
1439 "week_of_year", "day_of_year", "day_of_month",
1440 "day_of_week", "hour_of_day", "minute_of_hour",
1441 "second_of_minute"]:
1442 if attr in prop_dict:
1443 return attr
1444 return None
1445
1446 def get_smallest_missing_property_name(self):
1447 """Return the smallest unit missing from a truncated representation."""
1448 if not self._truncated:
1449 return None
1450 prop_dict = self.get_truncated_properties()
1451 attr_list = (("year_of_century", "century"),
1452 ("year_of_decade", "decade_of_century"),
1453 ("month_of_year", "year_of_century"),
1454 ("week_of_year", "year_of_century"),
1455 ("day_of_year", "year_of_century"),
1456 ("day_of_month", "month_of_year"),
1457 ("day_of_week", "week_of_year"),
1458 ("hour_of_day", "day_of_month"),
1459 ("minute_of_hour", "hour_of_day"),
1460 ("second_of_minute", "minute_of_hour"))
1461 for attr_key, attr_value in attr_list:
1462 if attr_key in prop_dict:
1463 return attr_value
1464 return None
1465
1466 def get_truncated_properties(self):
1467 """Return a map of properties if this is a truncated representation."""
1468 if not self._truncated:
1469 return None
1470 props = {}
1471 if self._truncated_property == "year_of_decade":
1472 props.update({"year_of_decade": self._year % 10})
1473 if self._truncated_property == "year_of_century":
1474 props.update({"year_of_century": self._year % 100})
1475 for attr in ["month_of_year", "week_of_year", "day_of_year",
1476 "day_of_month", "day_of_week", "hour_of_day",
1477 "minute_of_hour", "second_of_minute"]:
1478 value = getattr(self, "_{0}".format(attr))
1479 if value is not None:
1480 props.update({attr: value})
1481 return props
1482
1483 def add_truncated(self, year_of_century=None, year_of_decade=None,
1484 month_of_year=None, week_of_year=None, day_of_year=None,
1485 day_of_month=None, day_of_week=None, hour_of_day=None,
1486 minute_of_hour=None, second_of_minute=None):
1487 """Returns a copy of this TimePoint with truncated time properties
1488 added to it."""
1489 new = self._copy()
1490 if hour_of_day is not None and minute_of_hour is None:
1491 minute_of_hour = 0
1492 if ((hour_of_day is not None or minute_of_hour is not None) and
1493 second_of_minute is None):
1494 second_of_minute = 0
1495 if second_of_minute is not None or minute_of_hour is not None:
1496 new = new.to_hour_minute_second()
1497 if second_of_minute is not None:
1498 while new._second_of_minute != second_of_minute:
1499 new._second_of_minute += 1.0
1500 new._tick_over()
1501 if minute_of_hour is not None:
1502 while new._minute_of_hour != minute_of_hour:
1503 new._minute_of_hour += 1.0
1504 new._tick_over()
1505 if hour_of_day is not None:
1506 while new._hour_of_day != hour_of_day:
1507 new._hour_of_day += 1.0
1508 new._tick_over()
1509 if day_of_week is not None:
1510 new = new.to_week_date()
1511 while new._day_of_week != day_of_week:
1512 new._day_of_week += 1
1513 new._tick_over()
1514 if day_of_month is not None:
1515 new = new.to_calendar_date()
1516 while new._day_of_month != day_of_month:
1517 new._day_of_month += 1
1518 new._tick_over()
1519 if day_of_year is not None:
1520 new = new.to_ordinal_date()
1521 while new._day_of_year != day_of_year:
1522 new._day_of_year += 1
1523 new._tick_over()
1524 if week_of_year is not None:
1525 new = new.to_week_date()
1526 while new._week_of_year != week_of_year:
1527 new._week_of_year += 1
1528 new._tick_over()
1529 if month_of_year is not None:
1530 new = new.to_calendar_date()
1531 while new._month_of_year != month_of_year:
1532 new._month_of_year += 1
1533 new._tick_over()
1534 if year_of_decade is not None:
1535 new = new.to_calendar_date()
1536 new_year_of_decade = new._year % 10
1537 while new_year_of_decade != year_of_decade:
1538 new._year += 1
1539 new_year_of_decade = new._year % 10
1540 if year_of_century is not None:
1541 new = new.to_calendar_date()
1542 new_year_of_century = new._year % 100
1543 while new_year_of_century != year_of_century:
1544 new._year += 1
1545 new_year_of_century = new._year % 100
1546 return new
1547
1548 def __add__(self, other) -> "TimePoint":
1549 if isinstance(other, TimePoint):
1550 if self._truncated and not other._truncated:
1551 new = other.to_time_zone(self._time_zone)
1552 new = new.add_truncated(**self.get_truncated_properties())
1553 return new.to_time_zone(other._time_zone)
1554 if other._truncated and not self._truncated:
1555 return other + self
1556 if not isinstance(other, Duration):
1557 raise ValueError(
1558 "Invalid addition: can only add Duration or "
1559 "truncated TimePoint to TimePoint.")
1560 duration = other
1561 if duration.get_is_in_weeks():
1562 duration = duration.to_days()
1563 new = self._copy()
1564 if duration._seconds:
1565 if new._second_of_minute is None:
1566 if new._minute_of_hour is None:
1567 new._hour_of_day += (
1568 duration._seconds / float(CALENDAR.SECONDS_IN_HOUR))
1569 else:
1570 new._minute_of_hour += (
1571 duration._seconds / float(CALENDAR.SECONDS_IN_MINUTE))
1572 else:
1573 new._second_of_minute += duration._seconds
1574 new._tick_over()
1575 # FIXME: self._tick_over() broken for truncated TimePoints: issue #168
1576 if duration._minutes:
1577 if new._minute_of_hour is None:
1578 new._hour_of_day += (
1579 duration._minutes / float(CALENDAR.MINUTES_IN_HOUR))
1580 else:
1581 new._minute_of_hour += duration._minutes
1582 new._tick_over()
1583 if duration._hours:
1584 new._hour_of_day += duration._hours
1585 new._tick_over()
1586 if duration._days:
1587 if new.get_is_calendar_date():
1588 new._day_of_month += duration._days
1589 elif new.get_is_ordinal_date():
1590 new._day_of_year += duration._days
1591 else:
1592 new._day_of_week += duration._days
1593 new._tick_over()
1594 if duration._months:
1595 # This is the dangerous one...
1596 new = new.add_months(duration._months)
1597 if duration._years:
1598 new._year += duration._years
1599 if new.get_is_calendar_date():
1600 month_index = (
1601 (new._month_of_year - 1) % CALENDAR.MONTHS_IN_YEAR)
1602 if get_is_leap_year(new._year):
1603 max_day_in_new_month = (
1604 CALENDAR.DAYS_IN_MONTHS_LEAP[month_index])
1605 else:
1606 max_day_in_new_month = (
1607 CALENDAR.DAYS_IN_MONTHS[month_index])
1608 if new._day_of_month > max_day_in_new_month:
1609 # For example, when Feb 29 - 1 year = Feb 28.
1610 new._day_of_month = max_day_in_new_month
1611 elif new.get_is_ordinal_date():
1612 max_days_in_year = get_days_in_year(new._year)
1613 if max_days_in_year < new._day_of_year:
1614 new._day_of_year = max_days_in_year
1615 elif new.get_is_week_date():
1616 max_weeks_in_year = get_weeks_in_year(new._year)
1617 if max_weeks_in_year < new._week_of_year:
1618 new._week_of_year = max_weeks_in_year
1619 return new
1620
1621 def _copy(self) -> "TimePoint":
1622 """Returns an unlinked copy of this instance."""
1623 new_timepoint = TimePoint(is_empty_instance=True)
1624 for attr in self.__slots__:
1625 setattr(new_timepoint, attr, getattr(self, attr))
1626 new_timepoint._time_zone = self._time_zone._copy()
1627 return new_timepoint
1628
1629 def get_props(self) -> list:
1630 """Return the data properties of this TimePoint as a list of tuples."""
1631 props = []
1632 for attr in self.__slots__:
1633 value = getattr(self, attr, None)
1634 if callable(getattr(value, "_copy", None)):
1635 value = value._copy()
1636 props.append((attr[1:], value))
1637 # Have sliced attr string to remove leading underscore
1638 return props
1639
1640 def __hash__(self) -> int:
1641 if self._truncated:
1642 # TODO: Convert truncated TimePoints to UTC when not buggy
1643 return hash(
1644 tuple(getattr(self, attr) for attr in self.__slots__))
1645 point = self.to_utc()
1646 return hash((*point.get_calendar_date(),
1647 *point.get_hour_minute_second()))
1648
1649 def _cmp(self, other: "TimePoint", op: str) -> bool:
1650 """Compare self with other, using the chosen operator.
1651
1652 Args:
1653 op: The comparison operator/method, one of ["eq", "lt", "le",
1654 "gt", "ge"].
1655 """
1656 if not isinstance(other, TimePoint):
1657 return NotImplemented
1658 if self._truncated != other._truncated:
1659 raise ValueError(
1660 "Cannot compare truncated to non-truncated "
1661 "TimePoint: {0}, {1}".format(self, other))
1662 if self.get_props() == other.get_props():
1663 return True if op in ["eq", "le", "ge"] else False
1664 if self._truncated:
1665 # TODO: Convert truncated TimePoints to UTC when not buggy
1666 for attribute in self.__slots__:
1667 self_attr = getattr(self, attribute)
1668 other_attr = getattr(other, attribute)
1669 if self_attr != other_attr:
1670 return _operator_map[op](self_attr, other_attr)
1671 return True
1672 other = other.to_time_zone(self._time_zone)
1673 if self.get_is_calendar_date():
1674 my_date = self.get_calendar_date()
1675 other_date = other.get_calendar_date()
1676 else:
1677 my_date = self.get_ordinal_date()
1678 other_date = other.get_ordinal_date()
1679 my_datetime = [*my_date, self.get_second_of_day()]
1680 other_datetime = [*other_date, other.get_second_of_day()]
1681 return _operator_map[op](my_datetime, other_datetime)
1682
1683 def __eq__(self, other: "TimePoint") -> bool:
1684 return self._cmp(other, "eq")
1685
1686 def __lt__(self, other: "TimePoint") -> bool:
1687 return self._cmp(other, "lt")
1688
1689 def __le__(self, other: "TimePoint") -> bool:
1690 return self._cmp(other, "le")
1691
1692 def __gt__(self, other: "TimePoint") -> bool:
1693 return self._cmp(other, "gt")
1694
1695 def __ge__(self, other: "TimePoint") -> bool:
1696 return self._cmp(other, "ge")
1697
1698 def __sub__(self, other):
1699 if isinstance(other, TimePoint):
1700 if other > self:
1701 return -1 * (other - self)
1702 other = other.to_time_zone(self._time_zone)
1703 my_year, my_day_of_year = self.get_ordinal_date()
1704 other_year, other_day_of_year = other.get_ordinal_date()
1705 diff_day = my_day_of_year - other_day_of_year
1706 if my_year > other_year:
1707 diff_day += get_days_in_year_range(other_year, my_year - 1)
1708 else:
1709 diff_day -= get_days_in_year_range(my_year, other_year - 1)
1710 my_hour, my_minute, my_second = self.get_hour_minute_second()
1711 other_hour, other_minute, other_second = (
1712 other.get_hour_minute_second())
1713 diff_hour = my_hour - other_hour
1714 diff_minute = my_minute - other_minute
1715 diff_second = my_second - other_second
1716 if diff_second < 0:
1717 diff_minute -= 1
1718 diff_second += CALENDAR.SECONDS_IN_MINUTE
1719 if diff_minute < 0:
1720 diff_hour -= 1
1721 diff_minute += CALENDAR.MINUTES_IN_HOUR
1722 if diff_hour < 0:
1723 diff_day -= 1
1724 diff_hour += CALENDAR.HOURS_IN_DAY
1725 return Duration(
1726 days=diff_day, hours=diff_hour, minutes=diff_minute,
1727 seconds=diff_second)
1728 if not isinstance(other, Duration):
1729 raise TypeError(
1730 "Invalid subtraction type " +
1731 "'%s' - should be Duration." %
1732 type(other).__name__
1733 )
1734 duration = other
1735 return self.__add__(duration * -1)
1736
1737 def add_months(self, num_months):
1738 """Return a copy of this TimePoint with an amount of months added to
1739 it."""
1740 if num_months == 0:
1741 return self
1742 new = self._copy()
1743 was_ordinal_date = False
1744 was_week_date = False
1745 if not new.get_is_calendar_date():
1746 if new.get_is_ordinal_date():
1747 was_ordinal_date = True
1748 if new.get_is_week_date():
1749 was_week_date = True
1750 new = new.to_calendar_date()
1751 for _ in range(abs(num_months)):
1752 if num_months > 0:
1753 new._month_of_year += 1
1754 if new._month_of_year > CALENDAR.MONTHS_IN_YEAR:
1755 new._month_of_year -= CALENDAR.MONTHS_IN_YEAR
1756 new._year += 1
1757 if num_months < 0:
1758 new._month_of_year -= 1
1759 if new._month_of_year < 1:
1760 new._month_of_year += CALENDAR.MONTHS_IN_YEAR
1761 new._year -= 1
1762 month_index = (new._month_of_year - 1) % CALENDAR.MONTHS_IN_YEAR
1763 if get_is_leap_year(new._year):
1764 max_day_in_new_month = (
1765 CALENDAR.DAYS_IN_MONTHS_LEAP[month_index])
1766 else:
1767 max_day_in_new_month = (
1768 CALENDAR.DAYS_IN_MONTHS[month_index])
1769 if new._day_of_month > max_day_in_new_month:
1770 # For example, when 31 March + 1 month = 30 April.
1771 new._day_of_month = max_day_in_new_month
1772 new._tick_over()
1773 if was_ordinal_date:
1774 new = new.to_ordinal_date()
1775 if was_week_date:
1776 new = new.to_week_date()
1777 return new
1778
1779 def _tick_over(self, check_changes=False):
1780 """Correct all the units going from smallest to largest.
1781
1782 Args:
1783 check_changes (bool, optional): If True tick_over will return a
1784 dict of any changed fields.
1785
1786 Returns:
1787 dict: Dictionary of changed fields with before and after values
1788 if check_changes is True else None.
1789 """
1790 if check_changes:
1791 before = {key: getattr(self, key) for key in self.__slots__}
1792 if (self._hour_of_day is not None and
1793 self._minute_of_hour is not None):
1794 hours_remainder = self._hour_of_day - int(self._hour_of_day)
1795 self._hour_of_day -= hours_remainder
1796 self._minute_of_hour += (
1797 hours_remainder * CALENDAR.MINUTES_IN_HOUR)
1798 if (self._minute_of_hour is not None and
1799 self._second_of_minute is not None):
1800 minutes_remainder = (
1801 self._minute_of_hour - int(self._minute_of_hour))
1802 self._minute_of_hour -= minutes_remainder
1803 self._second_of_minute += (
1804 minutes_remainder * CALENDAR.SECONDS_IN_MINUTE)
1805 if self._second_of_minute is not None:
1806 num_minutes, seconds = divmod(self._second_of_minute,
1807 CALENDAR.SECONDS_IN_MINUTE)
1808 self._minute_of_hour += num_minutes
1809 self._second_of_minute = seconds
1810 if self._minute_of_hour is not None:
1811 num_hours, minutes = divmod(self._minute_of_hour,
1812 CALENDAR.MINUTES_IN_HOUR)
1813 self._hour_of_day += num_hours
1814 self._minute_of_hour = minutes
1815 if self._hour_of_day is not None:
1816 num_days, hours = divmod(self._hour_of_day, CALENDAR.HOURS_IN_DAY)
1817 num_days = int(num_days)
1818 if self._day_of_week is not None:
1819 self._day_of_week += num_days
1820 elif self._day_of_month is not None:
1821 self._day_of_month += num_days
1822 elif self._day_of_year is not None:
1823 self._day_of_year += num_days
1824 self._hour_of_day = hours
1825 if self._day_of_week is not None:
1826 num_weeks, days = divmod(
1827 self._day_of_week - 1, CALENDAR.DAYS_IN_WEEK)
1828 self._week_of_year += num_weeks
1829 self._day_of_week = days + 1
1830 if self._day_of_month is not None:
1831 self._tick_over_day_of_month()
1832 if self._day_of_year is not None:
1833 while self._day_of_year < 1:
1834 days_in_last_year = get_days_in_year(self._year - 1)
1835 self._day_of_year += days_in_last_year
1836 self._year -= 1
1837 while self._day_of_year > get_days_in_year(self._year):
1838 days_in_next_year = get_days_in_year(self._year + 1)
1839 self._day_of_year -= days_in_next_year
1840 self._year += 1
1841 if self._week_of_year is not None:
1842 while self._week_of_year < 1:
1843 weeks_in_last_year = get_weeks_in_year(self._year - 1)
1844 self._week_of_year += weeks_in_last_year
1845 self._year -= 1
1846 while self._week_of_year > get_weeks_in_year(self._year):
1847 weeks_in_this_year = get_weeks_in_year(self._year)
1848 self._week_of_year -= weeks_in_this_year
1849 self._year += 1
1850 if self._month_of_year is not None:
1851 while self._month_of_year < 1:
1852 self._month_of_year += CALENDAR.MONTHS_IN_YEAR
1853 self._year -= 1
1854 while self._month_of_year > CALENDAR.MONTHS_IN_YEAR:
1855 self._month_of_year -= CALENDAR.MONTHS_IN_YEAR
1856 self._year += 1
1857 if check_changes:
1858 return {
1859 key: (value, getattr(self, key))
1860 for key, value in before.items()
1861 if getattr(self, key) != value
1862 }
1863
1864 def _tick_over_day_of_month(self):
1865 if self._day_of_month < 1:
1866 num_days = 2
1867 for month, day in iter_months_days(
1868 self._year,
1869 month_of_year=self._month_of_year,
1870 day_of_month=1, in_reverse=True):
1871 num_days -= 1
1872 if num_days == self._day_of_month:
1873 self._month_of_year = month
1874 self._day_of_month = day
1875 break
1876 else: # no break
1877 start_year = self._year
1878 month = None
1879 day = None
1880 while num_days != self._day_of_month:
1881 start_year -= 1
1882 for month, day in iter_months_days(
1883 start_year, in_reverse=True):
1884 num_days -= 1
1885 if num_days == self._day_of_month:
1886 break
1887 self._year = start_year
1888 self._month_of_year = month
1889 self._day_of_month = day
1890 else:
1891 month_index = (self._month_of_year - 1) % CALENDAR.MONTHS_IN_YEAR
1892 if get_is_leap_year(self._year):
1893 max_day_in_month = CALENDAR.DAYS_IN_MONTHS_LEAP[month_index]
1894 else:
1895 max_day_in_month = CALENDAR.DAYS_IN_MONTHS[month_index]
1896 if self._day_of_month > max_day_in_month:
1897 num_days = 0
1898 for month, day in iter_months_days(
1899 self._year,
1900 month_of_year=self._month_of_year,
1901 day_of_month=1):
1902 num_days += 1
1903 if num_days == self._day_of_month:
1904 self._month_of_year = month
1905 self._day_of_month = day
1906 break
1907 else:
1908 start_year = self._year
1909 while num_days != self._day_of_month:
1910 start_year += 1
1911 for month, day in iter_months_days(start_year):
1912 num_days += 1
1913 if num_days == self._day_of_month:
1914 self._year = start_year
1915 self._month_of_year = month
1916 self._day_of_month = day
1917 return
1918
1919 def _check_bounds(self):
1920 """Check all values are within correct bounds."""
1921 _bounds_checker(self._month_of_year, "month_of_year",
1922 min_val=1, max_val=CALENDAR.MONTHS_IN_YEAR)
1923 if self._month_of_year is not None:
1924 if self._year is not None:
1925 max_days_in_month = get_days_in_month(self._month_of_year,
1926 self._year)
1927 else:
1928 max_days_in_month = get_days_in_month(self._month_of_year,
1929 year="leap")
1930 else:
1931 max_days_in_month = CALENDAR.MAX_DAYS_IN_MONTH
1932 _bounds_checker(self._day_of_month, "day_of_month",
1933 min_val=1, max_val=max_days_in_month)
1934 if self._year is not None:
1935 _bounds_checker(self._week_of_year, "week_of_year",
1936 min_val=1, max_val=get_weeks_in_year(self._year))
1937 _bounds_checker(self._day_of_year, "day_of_year",
1938 min_val=1, max_val=get_days_in_year(self._year))
1939 else:
1940 _bounds_checker(self._week_of_year, "week_of_year",
1941 min_val=1, max_val=CALENDAR.MAX_WEEKS_IN_YEAR)
1942 _bounds_checker(self._day_of_year, "day_of_year",
1943 min_val=1, max_val=CALENDAR.DAYS_IN_YEAR_LEAP)
1944 _bounds_checker(self._day_of_week, "day_of_week",
1945 min_val=1, max_val=CALENDAR.DAYS_IN_WEEK)
1946
1947 _bounds_checker(self._hour_of_day, "hour_of_day",
1948 min_val=0, max_val=CALENDAR.HOURS_IN_DAY)
1949 if self._hour_of_day == CALENDAR.HOURS_IN_DAY:
1950 _bounds_checker(self._minute_of_hour, "minute_of_hour",
1951 min_val=0, max_val=0)
1952 _bounds_checker(self._second_of_minute, "second_of_minute",
1953 min_val=0, max_val=0)
1954 else:
1955 _bounds_checker(self._minute_of_hour, "minute_of_hour",
1956 min_val=0, upper_val=CALENDAR.MINUTES_IN_HOUR)
1957 _bounds_checker(self._second_of_minute, "second_of_minute",
1958 min_val=0, upper_val=CALENDAR.SECONDS_IN_MINUTE)
1959
1960 def __str__(self, override_custom_dump_format=False,
1961 strftime_format=None):
1962 if self._num_expanded_year_digits not in TIMEPOINT_DUMPER_MAP:
1963 TIMEPOINT_DUMPER_MAP[self._num_expanded_year_digits] = (
1964 dumpers.TimePointDumper(self._num_expanded_year_digits))
1965 dumper = TIMEPOINT_DUMPER_MAP[self._num_expanded_year_digits]
1966 if strftime_format is not None:
1967 return dumper.strftime(self, strftime_format)
1968 if self._truncated:
1969 if self._truncated_dump_format and not override_custom_dump_format:
1970 return dumper.dump(self, self._truncated_dump_format)
1971 return dumper.dump(self, self._get_truncated_dump_format())
1972 if self._dump_format and not override_custom_dump_format:
1973 return dumper.dump(self, self._dump_format)
1974 return dumper.dump(self, self._get_dump_format())
1975
1976 def strftime(self, strftime_format):
1977 """Implement equivalent of Python 2's datetime.datetime.strftime.
1978
1979 Dump based on the format given in the strftime_format string.
1980 """
1981 return self.__str__(strftime_format=strftime_format)
1982
1983 def _get_dump_format(self):
1984 year_digits = 4 + self._num_expanded_year_digits
1985 year_string = "%0" + str(year_digits) + "d"
1986 if self._num_expanded_year_digits:
1987 if self._year < 0:
1988 year_string = "-" + year_string % abs(self._year)
1989 else:
1990 year_string = "+" + year_string % abs(self._year)
1991 elif self._year is not None and self._year < 0:
1992 raise OverflowError(
1993 "Year %s can only be represented in expanded format" %
1994 self._year
1995 )
1996 elif self._year is not None:
1997 year_string = year_string % self._year
1998
1999 if self.get_is_calendar_date():
2000 date_string = year_string + "-MM-DD"
2001 elif self.get_is_ordinal_date():
2002 date_string = year_string + "-DDD"
2003 elif self.get_is_week_date():
2004 date_string = year_string + "-Www-D"
2005 else:
2006 raise RuntimeError("TimePoint has inconsistent state, points "
2007 "must conform to calendar, ordinal or week "
2008 "dates.")
2009 time_string = "Thh"
2010 if self._minute_of_hour is None:
2011 time_string += ",ii"
2012 else:
2013 time_string += ":mm"
2014 if self._second_of_minute is None:
2015 time_string += ",nn"
2016 else:
2017 seconds_int = int(self._second_of_minute)
2018 time_string += ":ss"
2019 if seconds_int != self._second_of_minute:
2020 time_string += ",tt"
2021 if time_string:
2022 if self._time_zone._hours == 0 and self._time_zone._minutes == 0:
2023 time_string += "Z"
2024 else:
2025 time_string += "+hh:mm"
2026 return date_string + time_string
2027
2028 def _get_truncated_dump_format(self):
2029 year_string = "-"
2030 if self._truncated_property == "year_of_decade":
2031 year_string = "-" + "z"
2032 elif self._truncated_property == "year_of_century":
2033 if self._day_of_month is None and self._month_of_year is not None:
2034 year_string = "-YY"
2035 else:
2036 year_string = "YY"
2037 date_string = year_string
2038 if self._month_of_year is not None:
2039 date_string = year_string + "-MM"
2040 if self._day_of_month is not None:
2041 date_string += "-DD"
2042 elif self._day_of_month is not None:
2043 if year_string == "-":
2044 date_string = year_string + "--DD"
2045 else:
2046 date_string = year_string + "-DD"
2047 if self._day_of_year is not None:
2048 day_string = "DDD"
2049 if year_string == "-":
2050 date_string = year_string + day_string
2051 else:
2052 date_string = year_string + "-" + day_string
2053 if self._week_of_year is not None:
2054 if year_string == "-":
2055 date_string = year_string + "Www"
2056 else:
2057 date_string = year_string + "-Www"
2058 if self._day_of_week is not None:
2059 date_string += "-D"
2060 elif self._day_of_week is not None:
2061 if year_string == "-":
2062 date_string = year_string + "W-D"
2063 else:
2064 date_string = year_string + "-W-D"
2065 time_string = ""
2066 if (self._hour_of_day is None and
2067 (self._minute_of_hour is not None or
2068 self._second_of_minute is not None)):
2069 time_string = "T-"
2070 elif (self._hour_of_day is not None and
2071 int(self._hour_of_day) != self._hour_of_day):
2072 time_string = "Thh,ii"
2073 elif self._hour_of_day is not None:
2074 time_string = "Thh"
2075 if self._minute_of_hour is None and self._second_of_minute is not None:
2076 time_string += "-"
2077 elif (self._minute_of_hour is not None and
2078 int(self._minute_of_hour) != self._minute_of_hour):
2079 if self._hour_of_day is not None:
2080 time_string += ":"
2081 time_string += "mm,nn"
2082 elif self._minute_of_hour is not None:
2083 if self._hour_of_day is not None:
2084 time_string += ":"
2085 time_string += "mm"
2086 if self._second_of_minute is not None:
2087 seconds_int = int(self._second_of_minute)
2088 if self._minute_of_hour is not None:
2089 time_string += ":"
2090 time_string += "ss"
2091 if seconds_int != self._second_of_minute:
2092 time_string += ",tt"
2093 if time_string:
2094 if self._time_zone._hours == 0 and self._time_zone._minutes == 0:
2095 time_string += "Z"
2096 else:
2097 time_string += "+hh:mm"
2098 if date_string == "YY":
2099 date_string = "-YY"
2100 time_string = time_string.replace(":", "")
2101 if date_string == "-":
2102 date_string = ""
2103 return date_string + time_string
2104
2105 def __repr__(self):
2106 return "<{0}.{1}: {2}>".format(
2107 self.__module__, self.__class__.__name__, str(self))
2108
2109
2110 def _format_remainder(float_time_number):
2111 """Format a floating point remainder of a time unit."""
2112 string = "," + ("%f" % float_time_number)[2:].rstrip("0")
2113 if string == ",":
2114 return ""
2115 return string
2116
2117
2118 @lru_cache(maxsize=100000)
2119 def get_is_leap_year(year):
2120 """Return if year is a leap year."""
2121 year_is_leap = False
2122 for factor, is_leap_factor in CALENDAR.LEAP_YEAR_FACTOR_TRUTHS:
2123 if year % factor == 0:
2124 year_is_leap = is_leap_factor
2125 return year_is_leap
2126
2127
2128 def get_days_in_year_range(start_year, end_year):
2129 """Return the number of days within this year range (inclusive)."""
2130 return _get_days_in_year_range(start_year, end_year, CALENDAR.mode)
2131
2132
2133 @lru_cache(maxsize=100000)
2134 def _get_days_in_year_range(start_year, end_year, _):
2135 """Return the number of days within this year range (inclusive).
2136
2137 If end_year > start_year, return the days in start_year plus
2138 the days in the intervening years before end_year, plus the
2139 days in end_year.
2140
2141 If end_year == start_year, return the days in start_year.
2142
2143 If end_year < start_year, return 0.
2144
2145 """
2146 # Get the number of days discounting leap years.
2147 if start_year == end_year:
2148 return get_days_in_year(start_year)
2149 if start_year > end_year:
2150 return 0
2151 days = (end_year + 1 - start_year) * CALENDAR.DAYS_IN_YEAR
2152 diff_days_leap = (CALENDAR.DAYS_IN_YEAR_LEAP - CALENDAR.DAYS_IN_YEAR)
2153 for factor, is_leap_factor in CALENDAR.LEAP_YEAR_FACTOR_TRUTHS:
2154 num_corrections = 0
2155 if start_year % factor == 0:
2156 num_corrections += 1
2157 if end_year != start_year and end_year % factor == 0:
2158 num_corrections += 1
2159 factor_start_year = start_year + 1
2160 while (factor_start_year % factor != 0 and
2161 factor_start_year < end_year):
2162 factor_start_year += 1
2163 if factor_start_year < end_year:
2164 num_corrections += 1
2165 num_corrections += (
2166 end_year - (factor_start_year + 1)) // factor
2167 if is_leap_factor:
2168 days += num_corrections * diff_days_leap
2169 else:
2170 days -= num_corrections * diff_days_leap
2171 return days
2172
2173
2174 def get_days_in_year(year):
2175 """Return the number of days in this particular year."""
2176 return _get_days_in_year(year, CALENDAR.mode)
2177
2178
2179 @lru_cache(maxsize=100000)
2180 def _get_days_in_year(year, _):
2181 """Return the number of days in this particular year."""
2182 if get_is_leap_year(year):
2183 return CALENDAR.DAYS_IN_YEAR_LEAP
2184 return CALENDAR.DAYS_IN_YEAR
2185
2186
2187 def get_days_in_month(month_of_year, year="leap"):
2188 """Return the number of days in the month of this particular year.
2189 Year can also be "leap", or None for non-leap."""
2190 return _get_days_in_month(month_of_year, year, CALENDAR.mode)
2191
2192
2193 @lru_cache(maxsize=100000)
2194 def _get_days_in_month(month_of_year, year, _):
2195 """Return the number of days in the month of this particular year.
2196 Year can also be "leap", or None for non-leap."""
2197 month_index = month_of_year - 1
2198 if year is not None and (year == "leap" or get_is_leap_year(year)):
2199 return CALENDAR.DAYS_IN_MONTHS_LEAP[month_index]
2200 return CALENDAR.DAYS_IN_MONTHS[month_index]
2201
2202
2203 def get_weeks_in_year(year):
2204 """Return the number of calendar weeks in this week date year."""
2205 return _get_weeks_in_year(year, CALENDAR.mode)
2206
2207
2208 @lru_cache(maxsize=100000)
2209 def _get_weeks_in_year(year, _):
2210 """Return the number of calendar weeks in this week date year."""
2211 cal_year, cal_ord_days = get_ordinal_date_week_date_start(year)
2212 cal_year_next, cal_ord_days_next = get_ordinal_date_week_date_start(
2213 year + 1)
2214 diff_days = cal_ord_days_next - cal_ord_days
2215 for intervening_year in range(cal_year, cal_year_next):
2216 diff_days += get_days_in_year(intervening_year)
2217 return diff_days // CALENDAR.DAYS_IN_WEEK
2218
2219
2220 def get_calendar_date_from_ordinal_date(year, day_of_year):
2221 """Translate an ordinal date into a calendar date.
2222
2223 Returns the calendar year, calendar month, calendar day-of-month.
2224
2225 Arguments:
2226 year is an integer that denotes the ordinal date year
2227 day_of_year is an integer that denotes the ordinal day in the year.
2228
2229 """
2230 iter_num_days = 0
2231 for iter_month, iter_day in iter_months_days(year):
2232 iter_num_days += 1
2233 if iter_num_days == day_of_year:
2234 return year, iter_month, iter_day
2235 raise ValueError("Bad ordinal date: %s-%03d" % (year, day_of_year))
2236
2237
2238 def get_calendar_date_from_week_date(year, week_of_year, day_of_week):
2239 """Translate a week date into a calendar date.
2240
2241 Returns the calendar year, calendar month, calendar day-of-month.
2242
2243 Arguments:
2244 year is an integer that denotes the week date year (may differ
2245 from calendar year)
2246 week_of_year is an integer that denotes the week number in the year
2247 day_of_week is an integer that denotes the day of the week (1-7).
2248
2249 """
2250 num_days_week_year = (
2251 (week_of_year - 1) * CALENDAR.DAYS_IN_WEEK + day_of_week - 1)
2252 start_year, start_month, start_day = (
2253 get_calendar_date_week_date_start(year))
2254 if num_days_week_year == 0:
2255 return start_year, start_month, start_day
2256 total_iter_days = 0
2257 # Loop over the months and days left in the start year.
2258 for iter_month, iter_day in iter_months_days(
2259 start_year, month_of_year=start_month,
2260 day_of_month=start_day + 1):
2261 total_iter_days += 1
2262 if num_days_week_year == total_iter_days:
2263 return start_year, iter_month, iter_day
2264 if start_year < year:
2265 # We've only looped over the last year - now the current one.
2266 for iter_month, iter_day in iter_months_days(year):
2267 total_iter_days += 1
2268 if num_days_week_year == total_iter_days:
2269 return year, iter_month, iter_day
2270 for iter_month, iter_day in iter_months_days(year + 1):
2271 # Loop over the following year.
2272 total_iter_days += 1
2273 if num_days_week_year == total_iter_days:
2274 return year + 1, iter_month, iter_day
2275 raise ValueError("Bad week date: %s-W%02d-%s" % (year,
2276 week_of_year,
2277 day_of_week))
2278
2279
2280 def get_ordinal_date_from_calendar_date(year, month_of_year, day_of_month):
2281 """Translate a calendar date into an ordinal date.
2282
2283 Returns the ordinal year, calendar month, calendar day-of-month.
2284
2285 Arguments:
2286 year is an integer that denotes the year
2287 month_of_year is an integer that denotes the month number in the
2288 year.
2289 day_of_month is an integer that denotes the day number in the
2290 month_of_year.
2291
2292 """
2293 iter_num_days = 0
2294 for iter_month, iter_day in iter_months_days(year):
2295 iter_num_days += 1
2296 if iter_month == month_of_year and iter_day == day_of_month:
2297 return year, iter_num_days
2298 raise ValueError("Bad calendar date: %s-%02d-%02d" % (year,
2299 month_of_year,
2300 day_of_month))
2301
2302
2303 def get_ordinal_date_from_week_date(year, week_of_year, day_of_week):
2304 """Translate a week date into an ordinal date.
2305
2306 Returns the ordinal year, ordinal day-of-year.
2307
2308 Arguments:
2309 year is an integer that denotes the week date year (which may
2310 differ from the ordinal or calendar year)
2311 week_of_year is an integer that denotes the week number in the
2312 year.
2313 day_of_week is an integer that denotes the day number in the
2314 week_of_year.
2315
2316 """
2317 cal_year, cal_month, cal_day_of_month = get_calendar_date_from_week_date(
2318 year, week_of_year, day_of_week)
2319 return get_ordinal_date_from_calendar_date(
2320 cal_year, cal_month, cal_day_of_month)
2321
2322
2323 def get_week_date_from_calendar_date(year, month_of_year, day_of_month):
2324 """Translate a calendar date into an week date.
2325
2326 Returns the week date year, week-of-year, day-of-week.
2327
2328 Arguments:
2329 year is an integer that denotes the calendar year, which may
2330 differ from the week date year.
2331 month_of_year is an integer that denotes the month number in the
2332 above year.
2333 day_of_month is an integer that denotes the day number in the
2334 above month_of_year.
2335
2336 """
2337 prev_start = get_calendar_date_week_date_start(year - 1)
2338 this_start = get_calendar_date_week_date_start(year)
2339 next_start = get_calendar_date_week_date_start(year + 1)
2340
2341 cal_date = (year, month_of_year, day_of_month)
2342
2343 if prev_start <= cal_date < this_start:
2344 # This calendar date is in the previous week date year.
2345 start_year, start_month, start_day = prev_start
2346 week_date_start_year = year - 1
2347 elif this_start <= cal_date < next_start:
2348 # This calendar date is in the same week date year.
2349 start_year, start_month, start_day = this_start
2350 week_date_start_year = year
2351 else:
2352 # This calendar date is in the next week date year.
2353 start_year, start_month, start_day = next_start
2354 week_date_start_year = year + 1
2355
2356 total_iter_days = -1
2357 # A week date year can theoretically span 3 calendar years...
2358 for iter_month, iter_day in iter_months_days(start_year,
2359 month_of_year=start_month,
2360 day_of_month=start_day):
2361 total_iter_days += 1
2362 if (start_year == year and
2363 iter_month == month_of_year and
2364 iter_day == day_of_month):
2365 week_of_year = (total_iter_days // CALENDAR.DAYS_IN_WEEK) + 1
2366 day_of_week = (total_iter_days % CALENDAR.DAYS_IN_WEEK) + 1
2367 return week_date_start_year, week_of_year, day_of_week
2368
2369 for iter_start_year in [start_year + 1, start_year + 2]:
2370 # Look at following year when the calendar date is e.g. very early Jan.
2371 for iter_month, iter_day in iter_months_days(iter_start_year):
2372 total_iter_days += 1
2373 if (iter_start_year == year and
2374 iter_month == month_of_year and
2375 iter_day == day_of_month):
2376 week_of_year = (total_iter_days // CALENDAR.DAYS_IN_WEEK) + 1
2377 day_of_week = (total_iter_days % CALENDAR.DAYS_IN_WEEK) + 1
2378 return week_date_start_year, week_of_year, day_of_week
2379 raise ValueError("Bad calendar date: %s-%02d-%02d" % (year,
2380 month_of_year,
2381 day_of_month))
2382
2383
2384 def get_week_date_from_ordinal_date(year, day_of_year):
2385 """Translate an ordinal date into a week date.
2386
2387 Returns the week date year, week-of-year, day-of-week.
2388
2389 Arguments:
2390 year is an integer that denotes the ordinal date year, which
2391 may differ from the week date year.
2392 day_of_year is an integer that denotes the ordinal day in the year.
2393
2394 """
2395 year, month, day = get_calendar_date_from_ordinal_date(year, day_of_year)
2396 return get_week_date_from_calendar_date(year, month, day)
2397
2398
2399 def get_calendar_date_week_date_start(year):
2400 """Return the calendar date of the start of (week date) year."""
2401 return _get_calendar_date_week_date_start(year, CALENDAR.mode)
2402
2403
2404 @lru_cache(maxsize=100000)
2405 def _get_calendar_date_week_date_start(year, _):
2406 """Return the calendar date of the start of (week date) year."""
2407 ref_year, ref_month, ref_day = (
2408 CALENDAR.WEEK_DAY_START_REFERENCE["calendar"])
2409 ref_year, ref_ordinal_day = (
2410 CALENDAR.WEEK_DAY_START_REFERENCE["ordinal"])
2411 if year == ref_year:
2412 return ref_year, ref_month, ref_day
2413 # Calculate the weekday for 1 January in this calendar year.
2414 days_diff = 0
2415 if year > ref_year:
2416 days_diff = 1 - ref_ordinal_day
2417 days_diff += get_days_in_year_range(ref_year, year - 1)
2418 elif ref_year > year:
2419 days_diff = ref_ordinal_day - 2
2420 days_diff += get_days_in_year_range(year, ref_year - 1)
2421
2422 weekdays_diff = days_diff % CALENDAR.DAYS_IN_WEEK
2423 if year > ref_year:
2424 day_of_week_start_year = weekdays_diff + 1
2425 else:
2426 # Jan 1 as day of week.
2427 day_of_week_start_year = CALENDAR.DAYS_IN_WEEK - weekdays_diff
2428 if day_of_week_start_year == 1:
2429 return year, 1, 1
2430 if day_of_week_start_year > 4:
2431 # This week belongs to the previous year; get the next Monday.
2432 day = 1 + (8 - day_of_week_start_year)
2433 return year, 1, day
2434 # The week starts in the previous year - get the previous Monday.
2435 for month, day in iter_months_days(year - 1, in_reverse=True):
2436 day_of_week_start_year -= 1
2437 if day_of_week_start_year == 1:
2438 return year - 1, month, day
2439
2440
2441 def get_days_since_1_ad(year):
2442 """Return the number of days since Jan 1, 1 A.D. to the year end."""
2443 return _get_days_since_1_ad(year, CALENDAR.mode)
2444
2445
2446 @lru_cache(maxsize=100000)
2447 def _get_days_since_1_ad(year, _):
2448 """Return the number of days since Jan 1, 1 A.D. to the year end."""
2449 if year == 1:
2450 return get_days_in_year(year)
2451 elif year < 1:
2452 return 0
2453 return get_days_in_year_range(1, year)
2454
2455
2456 def get_ordinal_date_week_date_start(year):
2457 """Return the ordinal week date start for year (year, day-of-year)."""
2458 return _get_ordinal_date_week_date_start(year, CALENDAR.mode)
2459
2460
2461 @lru_cache(maxsize=100000)
2462 def _get_ordinal_date_week_date_start(year, _):
2463 """Return the ordinal week date start for year (year, day-of-year)."""
2464 cal_year, cal_month, cal_day = get_calendar_date_week_date_start(year)
2465 total_days = 0
2466 for iter_month, iter_day in iter_months_days(cal_year):
2467 total_days += 1
2468 if iter_month == cal_month and iter_day == cal_day:
2469 return cal_year, total_days
2470
2471
2472 def get_timepoint_for_now(utc=False):
2473 """Return a TimePoint at the current date/time.
2474
2475 Args:
2476 utc (bool): Whether the returned TimePoint should be in UTC or the
2477 local time zone.
2478 """
2479 import time
2480 return get_timepoint_from_seconds_since_unix_epoch(time.time(), utc=utc)
2481
2482
2483 def get_timepoint_from_seconds_since_unix_epoch(num_seconds, utc=False):
2484 """Return a TimePoint at a date/time specified in Unix time.
2485
2486 Args:
2487 num_seconds (float): The number of seconds since the Unix epoch.
2488 utc (bool): Whether the returned TimePoint should be in UTC or the
2489 local time zone.
2490
2491 Note that Unix time always counts 1 day = 86400 seconds, so if
2492 we implement leap seconds we need to make the distinction.
2493 """
2494 reference_timepoint = TimePoint(
2495 **CALENDAR.UNIX_EPOCH_DATE_TIME_REFERENCE_PROPERTIES)
2496 if not utc:
2497 reference_timepoint = reference_timepoint.to_local_time_zone()
2498 return reference_timepoint + Duration(seconds=float(num_seconds))
2499
2500
2501 def get_timepoint_properties_from_seconds_since_unix_epoch(num_seconds):
2502 """Translate Unix time into a dict of TimePoint constructor properties."""
2503 properties = dict(
2504 get_timepoint_from_seconds_since_unix_epoch(num_seconds).get_props())
2505 time_zone = properties.pop("time_zone")
2506 properties["time_zone_hour"] = time_zone._hours
2507 properties["time_zone_minute"] = time_zone._minutes
2508 return properties
2509
2510
2511 def iter_months_days(year, month_of_year=None, day_of_month=None,
2512 in_reverse=False):
2513 """Iterate over each day in each month of year.
2514
2515 year is an integer specifying the year to use.
2516 month_of_year is an optional integer, specifying a start month.
2517 day_of_month is an optional integer, specifying a start day.
2518 in_reverse is an optional boolean that reverses the iteration if
2519 True (default False).
2520
2521 """
2522 is_leap_year = get_is_leap_year(year)
2523 return _iter_months_days(
2524 is_leap_year, month_of_year, day_of_month, CALENDAR.mode, in_reverse)
2525
2526
2527 @lru_cache(maxsize=100000)
2528 def _iter_months_days(is_leap_year, month_of_year, day_of_month, _,
2529 in_reverse=False):
2530 if day_of_month is not None and month_of_year is None:
2531 raise ValueError("Need to specify start month as well as day.")
2532 source = CALENDAR.INDEXED_DAYS_IN_MONTHS
2533 if is_leap_year:
2534 source = CALENDAR.INDEXED_DAYS_IN_MONTHS_LEAP
2535 results = []
2536 if in_reverse:
2537 if month_of_year is None:
2538 for month_num, days in reversed(source):
2539 day_range = range(days, 0, -1)
2540 for day in day_range:
2541 results.append((month_num, day))
2542 else:
2543 for month_num, days in reversed(source):
2544 if month_num > month_of_year:
2545 continue
2546 elif month_num == month_of_year and day_of_month is not None:
2547 day_range = range(day_of_month, 0, -1)
2548 else:
2549 day_range = range(days, 0, -1)
2550 for day in day_range:
2551 results.append((month_num, day))
2552 else:
2553 if month_of_year is None:
2554 for month_num, days in source:
2555 day_range = range(1, days + 1)
2556 for day in day_range:
2557 results.append((month_num, day))
2558 else:
2559 for month_num, days in source[month_of_year - 1:]:
2560 if month_num == month_of_year and day_of_month is not None:
2561 day_range = range(day_of_month, days + 1)
2562 else:
2563 day_range = range(1, days + 1)
2564 for day in day_range:
2565 results.append((month_num, day))
2566 return results
2567
2568
2569 def _int_caster(number, name="number", allow_none=False):
2570 if allow_none and number is None:
2571 return None
2572 try:
2573 int_number = int(number)
2574 float_number = float(number)
2575 except (TypeError, ValueError) as num_exc:
2576 raise BadInputError(
2577 BadInputError.INT_CAST, name, number, num_exc)
2578 if float(int_number) != float_number:
2579 raise BadInputError(
2580 BadInputError.INT_REMAINDER, name, number)
2581 return int_number
2582
2583
2584 def _type_checker(*objects):
2585 """Helper function for checking the type of method arguments.
2586
2587 Args:
2588 *objects: Tuples of the form (value, name, *allowed_types):
2589
2590 Raises:
2591 BadInputError: If a value is not of the correct type.
2592 """
2593 for type_info in objects:
2594 value, name = type_info[:2]
2595 allowed_types = list(type_info[2:])
2596 none_is_allowed = False
2597 if None in allowed_types:
2598 if value is None:
2599 continue
2600 none_is_allowed = True
2601 allowed_types.remove(None)
2602 allowed_types.append(type(None))
2603 if allowed_types and isinstance(value, allowed_types[0]):
2604 continue
2605 if int in allowed_types and float not in allowed_types:
2606 value = _int_caster(value, name=name, allow_none=none_is_allowed)
2607 if any(isinstance(value, type_) for type_ in allowed_types):
2608 continue
2609 values_string = ""
2610 if allowed_types:
2611 values_string = " should be: "
2612 values_string += " or ".join(str(v) for v in allowed_types)
2613 raise BadInputError(
2614 BadInputError.TYPE, name, repr(value), values_string)
2615
2616
2617 def _bounds_checker(value, name, min_val, max_val=None, upper_val=None):
2618 """Helper function for checking the value of a property is within bounds.
2619
2620 Args:
2621 value (None, float): The value to check.
2622 name (str): Name of the property.
2623 min_val (float): Minimum value, inclusive.
2624 max_val (float, optional): Maximum value, inclusive.
2625 upper_val (float, optional): Upper limit of value, not inclusive.
2626
2627 Raises:
2628 BadInputError: If the value is out of bounds.
2629 """
2630 if (value is not None and
2631 (value < min_val or
2632 (max_val is not None and value > max_val) or
2633 (upper_val is not None and value >= upper_val))):
2634 raise BadInputError(BadInputError.OUT_OF_BOUNDS, name, value)
2635
2636
2637 PARSE_PROPERTY_TRANSLATORS = {
2638 "seconds_since_unix_epoch":
2639 get_timepoint_properties_from_seconds_since_unix_epoch
2640 }