Debian Codegraph @

recurring_ical_events/util.py

raw symbols SCIP
1 """Utility functions."""
2
3 from __future__ import annotations
4
5 import datetime
6 from functools import wraps
7 from typing import TYPE_CHECKING, Callable, Optional, Sequence
8
9 from recurring_ical_events.errors import PeriodEndBeforeStart
10
11 if TYPE_CHECKING:
12 from recurring_ical_events.adapters.component import ComponentAdapter
13 from recurring_ical_events.types import RecurrenceIDs, Time, Timestamp
14
15
16 def timestamp(dt: datetime.datetime) -> Timestamp:
17 """Return the time stamp of a datetime"""
18 return dt.timestamp()
19
20
21 def convert_to_date(date: Time) -> datetime.date:
22 """Converts a date or datetime to a date"""
23 return datetime.date(date.year, date.month, date.day)
24
25
26 def is_pytz(tzinfo: datetime.tzinfo | Time):
27 """Whether the time zone requires localize() and normalize().
28
29 pytz requires these funtions to be used in order to correctly use the
30 time zones after operations.
31 """
32 return hasattr(tzinfo, "localize")
33
34
35 def normalize_pytz(time: Time) -> Time:
36 """We have to normalize the time after a calculation if we use pytz."""
37 if is_pytz_dt(time):
38 return time.tzinfo.normalize(time)
39 return time
40
41
42 def is_date(time: Time) -> bool:
43 """Whether this is a date and not a datetime."""
44 return isinstance(time, datetime.date) and not isinstance(time, datetime.datetime)
45
46
47 def is_datetime(time: Time) -> bool:
48 """Whether this is a datetime and not a date."""
49 return isinstance(time, datetime.datetime)
50
51
52 def has_timezone(time: Time) -> bool:
53 """Whether this date/datetime has a timezone."""
54 return is_datetime(time) and time.tzinfo is not None
55
56
57 def convert_to_datetime(
58 date: Time, tzinfo: Optional[datetime.tzinfo]
59 ) -> datetime.datetime:
60 """Converts a date to a datetime.
61
62 Dates are converted to datetimes with tzinfo.
63 Datetimes loose their timezone if tzinfo is None.
64 Datetimes receive tzinfo as a timezone if they do not have a timezone.
65 Datetimes retain their timezone if they have one already (tzinfo is not None).
66 """
67 if is_date(date):
68 date = datetime.datetime(date.year, date.month, date.day) # noqa: DTZ001
69 if isinstance(date, datetime.datetime):
70 if date.tzinfo is None:
71 if tzinfo is not None:
72 if is_pytz(tzinfo):
73 return tzinfo.localize(date)
74 return date.replace(tzinfo=tzinfo)
75 elif tzinfo is None:
76 return normalize_pytz(date).replace(tzinfo=None)
77 return date
78 return date
79
80
81 def make_comparable(dates: Sequence[Time]) -> list[Time]:
82 """Make an list or tuple of dates comparable.
83
84 Returns an list.
85 """
86 tzinfo = None
87 all_dates = True
88 for date in dates:
89 if not is_date(date):
90 all_dates = False
91 if has_timezone(date):
92 tzinfo = date.tzinfo
93 break
94 if all_dates:
95 return dates
96 return [convert_to_datetime(date, tzinfo) for date in dates]
97
98
99 def time_span_contains_event(
100 span_start: Time,
101 span_stop: Time,
102 event_start: Time,
103 event_stop: Time,
104 comparable: bool = False, # noqa: FBT001
105 ) -> bool:
106 """Return whether an event should is included within a time span.
107
108 - span_start and span_stop define the time span
109 - event_start and event_stop define the event time
110 - comparable indicates whether the dates can be compared.
111 You can set it to True if you are sure you have timezones and
112 date/datetime correctly or used make_comparable() before.
113
114 Note that the stops are exlusive but the starts are inclusive.
115
116 This is an essential function of the module. It should be tested in
117 test/test_time_span_contains_event.py.
118
119 This raises a PeriodEndBeforeStart exception if a start is after an end.
120 """
121 if not comparable:
122 span_start, span_stop, event_start, event_stop = make_comparable(
123 (span_start, span_stop, event_start, event_stop)
124 )
125 if event_start > event_stop:
126 raise PeriodEndBeforeStart(
127 (
128 "the event must start before it ends"
129 f"(start: {event_start} end: {event_stop})"
130 ),
131 event_start,
132 event_stop,
133 )
134 if span_start > span_stop:
135 raise PeriodEndBeforeStart(
136 (
137 "the time span must start before it ends"
138 f"(start: {span_start} end: {span_stop})"
139 ),
140 span_start,
141 span_stop,
142 )
143 if event_start == event_stop:
144 if span_start == span_stop:
145 return event_start == span_start
146 return span_start <= event_start < span_stop
147 if span_start == span_stop:
148 return event_start <= span_start < event_stop
149 return event_start < span_stop and span_start < event_stop
150
151
152 def compare_greater(date1: Time, date2: Time) -> bool:
153 """Compare two dates if date1 > date2 and make them comparable before."""
154 date1, date2 = make_comparable((date1, date2))
155 return date1 > date2
156
157
158 def cmp(date1: Time, date2: Time) -> int:
159 """Compare two dates, like cmp().
160
161 Returns
162 -------
163 -1 if date1 < date2
164 0 if date1 = date2
165 1 if date1 > date2
166
167 """
168 # credits: https://www.geeksforgeeks.org/python-cmp-function/
169 # see https://stackoverflow.com/a/22490617/1320237
170 date1, date2 = make_comparable((date1, date2))
171 return (date1 > date2) - (date1 < date2)
172
173
174 def is_pytz_dt(time: Time) -> bool:
175 """Whether the time requires localize() and normalize().
176
177 pytz requires these funtions to be used in order to correctly use the
178 time zones after operations.
179 """
180 return isinstance(time, datetime.datetime) and is_pytz(time.tzinfo)
181
182
183 def cached_property(func: Callable) -> property:
184 """Cache the property value for speed up."""
185 name = f"_cached_{func.__name__}"
186 not_found = object()
187
188 @property
189 @wraps(func)
190 def cached_property(self: object):
191 value = self.__dict__.get(name, not_found)
192 if value is not_found:
193 self.__dict__[name] = value = func(self)
194 return value
195
196 return cached_property
197
198
199 def to_recurrence_ids(time: Time) -> RecurrenceIDs:
200 """Convert the time to a recurrence id so it can be hashed and recognized.
201
202 The first value should be used to identify a component as it is a datetime in UTC.
203 The other values can be used to look the component up.
204 """
205 # We are inside the Series calculation with this and want to identify
206 # a date. It is fair to assume that the timezones are the same now.
207 if not isinstance(time, datetime.datetime):
208 return (convert_to_datetime(time, None),)
209 if time.tzinfo is None:
210 return (time,)
211 return (
212 time.astimezone(datetime.timezone.utc).replace(tzinfo=None),
213 time.replace(tzinfo=None),
214 )
215
216
217 def with_highest_sequence(
218 adapter1: ComponentAdapter | None, adapter2: ComponentAdapter | None
219 ):
220 """Return the one with the highest sequence."""
221 return max(
222 adapter1,
223 adapter2,
224 key=lambda adapter: -1e10 if adapter is None else adapter.sequence,
225 )
226
227
228 def get_any(dictionary: dict, keys: Sequence[object], default: object = None):
229 """Get any item from the keys and return it."""
230 result = default
231 for key in keys:
232 result = dictionary.get(key, result)
233 return result
234
235
236 __all__ = [
237 "PeriodEndBeforeStart",
238 "cmp",
239 "convert_to_datetime",
240 "get_any",
241 "has_timezone",
242 "is_date",
243 "is_datetime",
244 "is_pytz",
245 "is_pytz_dt",
246 "make_comparable",
247 "normalize_pytz",
248 "time_span_contains_event",
249 "to_recurrence_ids",
250 "with_highest_sequence",
251 ]