timecore 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,326 @@
1
+ """BusinessCalendar: business days and business hours.
2
+
3
+ A business day is a day that is not a weekend day and not a holiday.
4
+ Business hours are the half-open wall-clock interval
5
+ ``[work_start, work_end)`` on a business day: work ends at
6
+ ``work_end`` itself, so 17:00 is not a business time when the working
7
+ day ends at 17:00.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterable
13
+
14
+ from ..core import Date, DateTime, Duration, LocalDateTime, Time, Weekday
15
+ from ._common import (
16
+ _add_days,
17
+ _require_date,
18
+ _require_instance,
19
+ _require_int,
20
+ _time_to_ns,
21
+ )
22
+ from .holidays import HolidayCalendar
23
+
24
+ __all__ = ["BusinessCalendar"]
25
+
26
+ #: Default start and end of the working day, as module-level singletons
27
+ #: so they can be used as signature defaults (``Time`` is immutable,
28
+ #: so sharing the instances is safe).
29
+ _DEFAULT_WORK_START = Time(9)
30
+ _DEFAULT_WORK_END = Time(17)
31
+
32
+
33
+ class BusinessCalendar:
34
+ """Business days and business hours for a country and work pattern.
35
+
36
+ Args:
37
+ country: ISO country code (``"US"``, ``"TW"``, ...) whose public
38
+ holidays are non-business days, or ``None`` for no holidays.
39
+ When ``country`` is given and ``holidays`` is ``None``, a
40
+ :class:`HolidayCalendar` is built from ``country`` and
41
+ ``subdiv``.
42
+ subdiv: Subdivision code (e.g. a US state) for the
43
+ country-derived holiday calendar; ignored unless ``country``
44
+ is given and ``holidays`` is ``None``.
45
+ weekend: The days of the week that are not business days.
46
+ Defaults to Saturday and Sunday.
47
+ work_start: The time the working day starts (inclusive).
48
+ work_end: The time the working day ends (exclusive).
49
+ holidays: An explicit :class:`HolidayCalendar` to use instead
50
+ of one derived from ``country``. When both are given, this
51
+ calendar takes precedence.
52
+
53
+ Example:
54
+ >>> cal = BusinessCalendar("US")
55
+ >>> cal.is_business_day(Date(2026, 12, 25))
56
+ False
57
+ >>> cal.is_business_day(Date(2026, 12, 28))
58
+ True
59
+ """
60
+
61
+ __slots__ = (
62
+ "_country",
63
+ "_holidays",
64
+ "_subdiv",
65
+ "_weekend",
66
+ "_weekend_set",
67
+ "_work_end",
68
+ "_work_start",
69
+ )
70
+
71
+ def __init__(
72
+ self,
73
+ country: str | None = None,
74
+ subdiv: str | None = None,
75
+ *,
76
+ weekend: Iterable[Weekday] = (Weekday.SATURDAY, Weekday.SUNDAY),
77
+ work_start: Time = _DEFAULT_WORK_START,
78
+ work_end: Time = _DEFAULT_WORK_END,
79
+ holidays: HolidayCalendar | None = None,
80
+ ) -> None:
81
+ if country is not None:
82
+ _require_instance(country, str, "country")
83
+ if subdiv is not None:
84
+ _require_instance(subdiv, str, "subdiv")
85
+ try:
86
+ weekend_values: tuple[object, ...] = tuple(weekend)
87
+ except TypeError as exc:
88
+ raise TypeError(
89
+ f"weekend must be an iterable of Weekday, got {type(weekend).__name__}"
90
+ ) from exc
91
+ validated_weekend = [
92
+ _require_instance(day, Weekday, "weekend") for day in weekend_values
93
+ ]
94
+ _require_instance(work_start, Time, "work_start")
95
+ _require_instance(work_end, Time, "work_end")
96
+ if work_start >= work_end:
97
+ raise ValueError(
98
+ f"work_start {work_start} must be before work_end {work_end}"
99
+ )
100
+ if holidays is not None:
101
+ _require_instance(holidays, HolidayCalendar, "holidays")
102
+ self._country = country
103
+ self._subdiv = subdiv
104
+ # Deduplicate, preserving the given order.
105
+ self._weekend = tuple(dict.fromkeys(validated_weekend))
106
+ self._weekend_set = frozenset(self._weekend)
107
+ self._work_start = work_start
108
+ self._work_end = work_end
109
+ if holidays is not None:
110
+ self._holidays = holidays
111
+ elif country is not None:
112
+ self._holidays = HolidayCalendar(country, subdiv)
113
+ else:
114
+ self._holidays = None
115
+
116
+ @property
117
+ def country(self) -> str | None:
118
+ """The country code, or ``None`` if no country was given."""
119
+ return self._country
120
+
121
+ @property
122
+ def subdiv(self) -> str | None:
123
+ """The subdivision code, or ``None``."""
124
+ return self._subdiv
125
+
126
+ @property
127
+ def weekend(self) -> tuple[Weekday, ...]:
128
+ """The weekend days, as a tuple of :class:`~timecore.core.Weekday`."""
129
+ return self._weekend
130
+
131
+ @property
132
+ def work_start(self) -> Time:
133
+ """The time the working day starts (inclusive)."""
134
+ return self._work_start
135
+
136
+ @property
137
+ def work_end(self) -> Time:
138
+ """The time the working day ends (exclusive)."""
139
+ return self._work_end
140
+
141
+ @property
142
+ def holidays(self) -> HolidayCalendar | None:
143
+ """The holiday calendar, or ``None`` if this calendar has no holidays."""
144
+ return self._holidays
145
+
146
+ def is_business_day(self, date: Date) -> bool:
147
+ """Return ``True`` if ``date`` is a business day.
148
+
149
+ A business day is a day whose weekday is not in ``weekend``
150
+ and that is not a holiday in this calendar's holiday calendar
151
+ (if any).
152
+ """
153
+ date = _require_date(date, "date")
154
+ if date.weekday in self._weekend_set:
155
+ return False
156
+ return self._holidays is None or not self._holidays.is_holiday(date)
157
+
158
+ def is_business_time(self, value: DateTime | LocalDateTime) -> bool:
159
+ """Return ``True`` if ``value`` falls inside business hours.
160
+
161
+ ``value`` must be a business day and its time of day must lie
162
+ in the half-open interval ``[work_start, work_end)``.
163
+ For a :class:`~timecore.core.DateTime` the wall time in its
164
+ own time zone is used.
165
+ """
166
+ local = self._to_local(value, "is_business_time() value")
167
+ if not self.is_business_day(local.date()):
168
+ return False
169
+ moment_ns = _time_to_ns(local.time())
170
+ return _time_to_ns(self._work_start) <= moment_ns < _time_to_ns(self._work_end)
171
+
172
+ def business_days_between(self, start: Date, end: Date) -> int:
173
+ """Return the number of business days in ``[start, end)``.
174
+
175
+ The range is half-open: ``end`` itself is not counted, and an
176
+ empty range returns 0.
177
+
178
+ Raises:
179
+ TypeError: If ``start`` or ``end`` is not a
180
+ :class:`~timecore.core.Date`.
181
+ ValueError: If ``start`` is after ``end``.
182
+ """
183
+ start = _require_date(start, "start")
184
+ end = _require_date(end, "end")
185
+ if start > end:
186
+ raise ValueError(f"start {start} must not be after end {end}")
187
+ count = 0
188
+ day = start
189
+ while day < end:
190
+ if self.is_business_day(day):
191
+ count += 1
192
+ day = _add_days(day, 1)
193
+ return count
194
+
195
+ def add_business_days(self, date: Date, n: int) -> Date:
196
+ """Return the date ``n`` business days after ``date``.
197
+
198
+ Only business days are counted: stepping starts from ``date``
199
+ itself, which is never counted, so adding 1 to a Friday lands
200
+ on the following Monday (or later, across a holiday). A
201
+ negative ``n`` steps backwards. Adding 0 returns ``date``
202
+ unchanged, even if it is not a business day.
203
+ """
204
+ date = _require_date(date, "date")
205
+ n = _require_int(n, "n")
206
+ if n == 0:
207
+ return date
208
+ step = 1 if n > 0 else -1
209
+ remaining = abs(n)
210
+ day = date
211
+ while remaining > 0:
212
+ day = _add_days(day, step)
213
+ if self.is_business_day(day):
214
+ remaining -= 1
215
+ return day
216
+
217
+ def next_business_day(self, date: Date) -> Date:
218
+ """Return the next business day strictly after ``date``."""
219
+ date = _require_date(date, "date")
220
+ day = _add_days(date, 1)
221
+ while not self.is_business_day(day):
222
+ day = _add_days(day, 1)
223
+ return day
224
+
225
+ def previous_business_day(self, date: Date) -> Date:
226
+ """Return the previous business day strictly before ``date``."""
227
+ date = _require_date(date, "date")
228
+ day = _add_days(date, -1)
229
+ while not self.is_business_day(day):
230
+ day = _add_days(day, -1)
231
+ return day
232
+
233
+ def business_hours_between(
234
+ self, start: DateTime | LocalDateTime, end: DateTime | LocalDateTime
235
+ ) -> Duration:
236
+ """Return the business time inside ``[start, end)`` as a :class:`Duration`.
237
+
238
+ Only time within ``[work_start, work_end)`` on business days
239
+ counts: nights, weekends, and holidays contribute nothing.
240
+ Both arguments must be the same type
241
+ (:class:`~timecore.core.DateTime` or
242
+ :class:`~timecore.core.LocalDateTime`); for ``DateTime``
243
+ inputs the wall time in each value's own time zone is used,
244
+ so a DST transition day still counts its full wall-clock
245
+ working day.
246
+
247
+ Raises:
248
+ TypeError: If either argument is not a ``DateTime`` or
249
+ ``LocalDateTime``, or the two have different types.
250
+ ValueError: If ``start`` is after ``end``.
251
+ """
252
+ start_local = self._to_local(start, "business_hours_between() start")
253
+ end_local = self._to_local(end, "business_hours_between() end")
254
+ if type(start) is not type(end):
255
+ raise TypeError(
256
+ "business_hours_between() start and end must have the same type, "
257
+ f"got {type(start).__name__} and {type(end).__name__}"
258
+ )
259
+ if start_local > end_local:
260
+ raise ValueError(f"start {start} must not be after end {end}")
261
+ if start_local == end_local:
262
+ return Duration.ZERO
263
+
264
+ work_start_ns = _time_to_ns(self._work_start)
265
+ work_end_ns = _time_to_ns(self._work_end)
266
+ start_day = start_local.date()
267
+ end_day = end_local.date()
268
+ total_ns = 0
269
+ day = start_day
270
+ while day <= end_day:
271
+ if self.is_business_day(day):
272
+ if day == start_day and day == end_day:
273
+ total_ns += _overlap_ns(
274
+ _time_to_ns(start_local.time()),
275
+ _time_to_ns(end_local.time()),
276
+ work_start_ns,
277
+ work_end_ns,
278
+ )
279
+ elif day == start_day:
280
+ total_ns += _overlap_ns(
281
+ _time_to_ns(start_local.time()),
282
+ work_end_ns,
283
+ work_start_ns,
284
+ work_end_ns,
285
+ )
286
+ elif day == end_day:
287
+ total_ns += _overlap_ns(
288
+ work_start_ns,
289
+ _time_to_ns(end_local.time()),
290
+ work_start_ns,
291
+ work_end_ns,
292
+ )
293
+ else:
294
+ total_ns += work_end_ns - work_start_ns
295
+ day = _add_days(day, 1)
296
+ return Duration(nanoseconds=total_ns)
297
+
298
+ @staticmethod
299
+ def _to_local(value: object, what: str) -> LocalDateTime:
300
+ """Return ``value`` as a :class:`LocalDateTime` (wall time)."""
301
+ if isinstance(value, DateTime):
302
+ return value.to_local_datetime()
303
+ if isinstance(value, LocalDateTime):
304
+ return value
305
+ raise TypeError(
306
+ f"{what} must be a DateTime or LocalDateTime, got {type(value).__name__}"
307
+ )
308
+
309
+ def __repr__(self) -> str:
310
+ parts: list[str] = []
311
+ if self._country is not None:
312
+ parts.append(f"country={self._country!r}")
313
+ if self._subdiv is not None:
314
+ parts.append(f"subdiv={self._subdiv!r}")
315
+ weekend = ", ".join(day.name for day in self._weekend)
316
+ parts.append(f"weekend=({weekend})")
317
+ parts.append(f"work_start={self._work_start!r}")
318
+ parts.append(f"work_end={self._work_end!r}")
319
+ return f"BusinessCalendar({', '.join(parts)})"
320
+
321
+
322
+ def _overlap_ns(
323
+ start_ns: int, end_ns: int, window_start_ns: int, window_end_ns: int
324
+ ) -> int:
325
+ """Return the overlap, in nanoseconds, of ``[start, end)`` with a window."""
326
+ return max(0, min(end_ns, window_end_ns) - max(start_ns, window_start_ns))
@@ -0,0 +1,92 @@
1
+ """Calendar: stateless Gregorian calendar calculations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import calendar as _stdlib_calendar
6
+
7
+ from ..core import Date
8
+ from ._common import _require_date, _require_int
9
+
10
+ __all__ = ["Calendar"]
11
+
12
+
13
+ class Calendar:
14
+ """Stateless Gregorian calendar calculations.
15
+
16
+ All methods are static; there is no state to construct. Years use
17
+ the proleptic Gregorian calendar and must be in the range 1-9999
18
+ (the range supported by the underlying standard-library calendar).
19
+ """
20
+
21
+ @staticmethod
22
+ def days_in_month(year: int, month: int) -> int:
23
+ """Return the number of days in ``month`` of ``year``.
24
+
25
+ Example:
26
+ >>> Calendar.days_in_month(2024, 2)
27
+ 29
28
+
29
+ Raises:
30
+ TypeError: If ``year`` or ``month`` is not an int.
31
+ ValueError: If ``month`` is not in 1-12 or ``year`` is not
32
+ in 1-9999.
33
+ """
34
+ year = _require_int(year, "year")
35
+ month = _require_int(month, "month")
36
+ return _stdlib_calendar.monthrange(year, month)[1]
37
+
38
+ @staticmethod
39
+ def days_in_year(year: int) -> int:
40
+ """Return the number of days in ``year``: 366 in a leap year, else 365.
41
+
42
+ Example:
43
+ >>> Calendar.days_in_year(2024)
44
+ 366
45
+
46
+ Raises:
47
+ TypeError: If ``year`` is not an int.
48
+ ValueError: If ``year`` is not in 1-9999.
49
+ """
50
+ return 366 if Calendar.is_leap_year(year) else 365
51
+
52
+ @staticmethod
53
+ def is_leap_year(year: int) -> bool:
54
+ """Return ``True`` if ``year`` is a leap year in the Gregorian calendar.
55
+
56
+ A year is a leap year if it is divisible by 4, except century
57
+ years, which are leap years only when divisible by 400
58
+ (so 2000 is a leap year but 1900 is not).
59
+
60
+ Example:
61
+ >>> Calendar.is_leap_year(2000)
62
+ True
63
+ >>> Calendar.is_leap_year(1900)
64
+ False
65
+
66
+ Raises:
67
+ TypeError: If ``year`` is not an int.
68
+ ValueError: If ``year`` is not in 1-9999.
69
+ """
70
+ year = _require_int(year, "year")
71
+ if not 1 <= year <= 9999:
72
+ raise ValueError(f"year must be in 1-9999, got {year}")
73
+ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
74
+
75
+ @staticmethod
76
+ def iso_calendar(date: Date) -> tuple[int, int, int]:
77
+ """Return the ISO calendar ``(year, week, weekday)`` for ``date``.
78
+
79
+ The ISO year can differ from the calendar year near 1 January
80
+ and 31 December. The week is the ISO week number (1-53) and the
81
+ weekday follows ISO 8601: Monday is 1 and Sunday is 7.
82
+
83
+ Example:
84
+ >>> Calendar.iso_calendar(Date(2021, 1, 1))
85
+ (2020, 53, 5)
86
+
87
+ Raises:
88
+ TypeError: If ``date`` is not a :class:`~timecore.core.Date`.
89
+ """
90
+ date = _require_date(date, "date")
91
+ iso = date.to_date().isocalendar()
92
+ return (iso.year, iso.week, iso.weekday)
@@ -0,0 +1,168 @@
1
+ """HolidayCalendar: public holidays for a country.
2
+
3
+ The ``holidays`` library is used internally as the data source and is
4
+ never exposed: no ``holidays`` type appears in any signature, return
5
+ value, or ``repr``, and ``holidays`` exceptions are mapped to
6
+ ``ValueError`` at the boundary.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import holidays as _holidays
12
+
13
+ from ..core import Date
14
+ from ._common import _require_date, _require_str
15
+
16
+ __all__ = ["HolidayCalendar"]
17
+
18
+ #: How far ahead (in years) ``next_holiday`` searches before giving up
19
+ #: and returning ``None``. Every supported country has at least one
20
+ #: holiday per year, so in practice the search ends in the first year.
21
+ _NEXT_SEARCH_YEARS = 20
22
+
23
+ #: How far back (in years) ``previous_holiday`` searches.
24
+ _PREVIOUS_SEARCH_YEARS = 20
25
+
26
+
27
+ class HolidayCalendar:
28
+ """Public holidays for a country (and optionally a subdivision).
29
+
30
+ ``country`` is an ISO 3166-1 alpha-2 code (``"US"``, ``"TW"``) or
31
+ any other country key the ``holidays`` library supports;
32
+ ``subdiv`` is a subdivision code such as a US state (``"CA"``)
33
+ or ``None`` for the country-wide holidays only.
34
+
35
+ The calendar is lazy: holiday data for a year is loaded only when
36
+ a query touches that year.
37
+
38
+ Example:
39
+ >>> cal = HolidayCalendar("US")
40
+ >>> cal.is_holiday(Date(2026, 12, 25))
41
+ True
42
+ """
43
+
44
+ __slots__ = ("_country", "_holidays", "_subdiv")
45
+
46
+ def __init__(self, country: str, subdiv: str | None = None) -> None:
47
+ self._country = _require_str(country, "country")
48
+ self._subdiv = _require_str(subdiv, "subdiv") if subdiv is not None else None
49
+ try:
50
+ # No ``years`` here: the base expands lazily, year by year,
51
+ # as dates are queried. Construction validates the country
52
+ # and subdivision eagerly.
53
+ self._holidays = _holidays.country_holidays(country, subdiv=subdiv)
54
+ except NotImplementedError as exc:
55
+ raise ValueError(
56
+ f"unknown country or subdivision: {country!r}"
57
+ + (f", subdiv {subdiv!r}" if subdiv is not None else "")
58
+ ) from exc
59
+
60
+ @property
61
+ def country(self) -> str:
62
+ """The country code this calendar covers."""
63
+ return self._country
64
+
65
+ @property
66
+ def subdiv(self) -> str | None:
67
+ """The subdivision code, or ``None`` for country-wide holidays only."""
68
+ return self._subdiv
69
+
70
+ def _holidays_for_years(self, years: range) -> _holidays.HolidayBase:
71
+ """Build a ``holidays`` base pre-populated for ``years``."""
72
+ try:
73
+ return _holidays.country_holidays(
74
+ self._country, subdiv=self._subdiv, years=list(years)
75
+ )
76
+ except NotImplementedError as exc:
77
+ # Unreachable in practice: the country/subdivision were
78
+ # validated in __init__.
79
+ raise ValueError(
80
+ f"unknown country or subdivision: {self._country!r}"
81
+ ) from exc
82
+
83
+ def is_holiday(self, date: Date) -> bool:
84
+ """Return ``True`` if ``date`` is a public holiday in this calendar."""
85
+ date = _require_date(date, "date")
86
+ return date.to_date() in self._holidays
87
+
88
+ def contains(self, date: Date) -> bool:
89
+ """Return ``True`` if ``date`` is a public holiday (same as :meth:`is_holiday`)."""
90
+ return self.is_holiday(date)
91
+
92
+ def holidays_between(self, start: Date, end: Date) -> list[tuple[Date, str]]:
93
+ """Return the holidays in the half-open range ``[start, end)``.
94
+
95
+ The result is a list of ``(date, name)`` pairs sorted by date.
96
+ A day with more than one holiday is reported once, with the
97
+ names joined by ``"; "``. An empty range returns ``[]``.
98
+
99
+ Raises:
100
+ TypeError: If ``start`` or ``end`` is not a
101
+ :class:`~timecore.core.Date`.
102
+ ValueError: If ``start`` is after ``end``.
103
+ """
104
+ start = _require_date(start, "start")
105
+ end = _require_date(end, "end")
106
+ if start > end:
107
+ raise ValueError(f"start {start} must not be after end {end}")
108
+ if start == end:
109
+ return []
110
+ base = self._holidays_for_years(range(start.year, end.year + 1))
111
+ result: list[tuple[Date, str]] = []
112
+ for day in sorted(base):
113
+ if start.to_date() <= day < end.to_date():
114
+ names = base.get_list(day)
115
+ result.append((Date.from_date(day), "; ".join(names)))
116
+ return result
117
+
118
+ def next_holiday(self, date: Date) -> tuple[Date, str] | None:
119
+ """Return the next holiday strictly after ``date``.
120
+
121
+ The result is a ``(date, name)`` pair, or ``None`` if no
122
+ holiday is found within the search horizon (20 years).
123
+ A holiday falling on ``date`` itself is not returned.
124
+ """
125
+ date = _require_date(date, "date")
126
+ target = date.to_date()
127
+ year = date.year
128
+ searched = 0
129
+ while searched < _NEXT_SEARCH_YEARS:
130
+ chunk = range(year, min(year + 2, 10000))
131
+ if not chunk:
132
+ return None
133
+ base = self._holidays_for_years(chunk)
134
+ candidates = [day for day in base if day > target]
135
+ if candidates:
136
+ day = min(candidates)
137
+ return (Date.from_date(day), "; ".join(base.get_list(day)))
138
+ year = chunk.stop
139
+ searched += len(chunk)
140
+ return None
141
+
142
+ def previous_holiday(self, date: Date) -> tuple[Date, str] | None:
143
+ """Return the previous holiday strictly before ``date``.
144
+
145
+ The result is a ``(date, name)`` pair, or ``None`` if no
146
+ holiday is found within the search horizon (20 years back,
147
+ stopping at year 1). A holiday falling on ``date`` itself is
148
+ not returned.
149
+ """
150
+ date = _require_date(date, "date")
151
+ target = date.to_date()
152
+ year = date.year
153
+ searched = 0
154
+ while searched < _PREVIOUS_SEARCH_YEARS and year >= 1:
155
+ chunk = range(max(1, year - 1), year + 1)
156
+ base = self._holidays_for_years(chunk)
157
+ candidates = [day for day in base if day < target]
158
+ if candidates:
159
+ day = max(candidates)
160
+ return (Date.from_date(day), "; ".join(base.get_list(day)))
161
+ year = chunk.start - 1
162
+ searched += len(chunk)
163
+ return None
164
+
165
+ def __repr__(self) -> str:
166
+ if self._subdiv is None:
167
+ return f"HolidayCalendar(country={self._country!r})"
168
+ return f"HolidayCalendar(country={self._country!r}, subdiv={self._subdiv!r})"
@@ -0,0 +1,14 @@
1
+ """Clocks and timers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .clock import Clock, FixedClock, OffsetClock, SystemClock
6
+ from .timer import Timer
7
+
8
+ __all__ = [
9
+ "Clock",
10
+ "FixedClock",
11
+ "OffsetClock",
12
+ "SystemClock",
13
+ "Timer",
14
+ ]