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.
timecore/core/date.py ADDED
@@ -0,0 +1,257 @@
1
+ """Date: a calendar date without a time component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date as _StdDate
6
+ from datetime import datetime as _StdDateTime
7
+ from typing import TYPE_CHECKING
8
+
9
+ import whenever
10
+
11
+ from ._common import (
12
+ Clock,
13
+ _date_today,
14
+ _format_value,
15
+ _instant_from_clock,
16
+ _map_parse_errors,
17
+ _map_whenever_errors,
18
+ _require_instance,
19
+ _require_str,
20
+ _require_whole_days,
21
+ _resolve_timezone,
22
+ _strptime,
23
+ )
24
+ from .duration import Duration
25
+ from .period import Period
26
+ from .time import Time
27
+ from .weekday import Weekday
28
+
29
+ if TYPE_CHECKING:
30
+ from .local_datetime import LocalDateTime
31
+ from .timezone import TimeZone
32
+
33
+ __all__ = ["Date"]
34
+
35
+
36
+ class Date:
37
+ """A calendar date without a time component.
38
+
39
+ Example:
40
+ >>> Date(2027, 1, 1)
41
+ Date(2027, 1, 1)
42
+ """
43
+
44
+ __slots__ = ("_inner",)
45
+
46
+ # The wrapped whenever value; declared here so pyright knows its type.
47
+ _inner: whenever.Date
48
+
49
+ def __init__(self, year: int, month: int, day: int) -> None:
50
+ with _map_whenever_errors():
51
+ self._inner = whenever.Date(year, month, day)
52
+
53
+ @classmethod
54
+ def from_whenever(cls, inner: whenever.Date) -> Date:
55
+ """Wrap a whenever ``Date``.
56
+
57
+ Internal constructor; not part of the public API.
58
+ """
59
+ obj = cls.__new__(cls)
60
+ obj._inner = inner
61
+ return obj
62
+
63
+ @classmethod
64
+ def today(
65
+ cls,
66
+ *,
67
+ timezone: TimeZone | str | None = None,
68
+ clock: Clock | None = None,
69
+ ) -> Date:
70
+ """Return the current date in ``timezone`` (default: local zone).
71
+
72
+ Pass ``clock`` (an object with a ``now() -> Instant`` method) to
73
+ determine "now" deterministically, e.g. in tests.
74
+ """
75
+ instant = _instant_from_clock(clock)
76
+ tz = _resolve_timezone(timezone)
77
+ if instant is not None:
78
+ return instant.to_datetime(tz).to_local_datetime().date()
79
+ with _map_whenever_errors():
80
+ return cls.from_whenever(_date_today(tz.key))
81
+
82
+ @classmethod
83
+ def parse(cls, text: str, *, format: str | None = None) -> Date:
84
+ """Parse an ISO 8601 date such as ``"2026-01-15"``.
85
+
86
+ With ``format``, parse with a ``strftime`` pattern instead
87
+ (English month names only, locale-independent).
88
+
89
+ Raises:
90
+ ParseError: If ``text`` is not a valid date in the given form.
91
+ """
92
+ text = _require_str(text, "Date.parse()")
93
+ if format is not None:
94
+ format = _require_str(format, "Date.parse() format")
95
+ parsed = _strptime(text, format)
96
+ return cls(parsed.year, parsed.month, parsed.day)
97
+ with _map_parse_errors():
98
+ return cls.from_whenever(whenever.Date.parse_iso(text))
99
+
100
+ @classmethod
101
+ def from_date(cls, value: _StdDate) -> Date:
102
+ """Create a :class:`Date` from a standard-library ``date``."""
103
+ value = _require_instance(value, _StdDate, "Date.from_date()")
104
+ if isinstance(value, _StdDateTime):
105
+ raise TypeError(
106
+ "Date.from_date() expects a datetime.date, not a datetime; "
107
+ "use LocalDateTime.from_datetime() or DateTime.from_datetime()"
108
+ )
109
+ with _map_whenever_errors():
110
+ return cls.from_whenever(whenever.Date(value))
111
+
112
+ def to_date(self) -> _StdDate:
113
+ """Convert to a standard-library ``date``."""
114
+ return self._inner.to_stdlib()
115
+
116
+ def to_local_datetime(self, time: Time | None = None) -> LocalDateTime:
117
+ """Combine this date with ``time`` (default: midnight) into a ``LocalDateTime``."""
118
+ from .local_datetime import LocalDateTime
119
+
120
+ if time is None:
121
+ return LocalDateTime(self.year, self.month, self.day)
122
+ time = _require_instance(time, Time, "Date.to_local_datetime() time")
123
+ return LocalDateTime(
124
+ self.year,
125
+ self.month,
126
+ self.day,
127
+ time.hour,
128
+ time.minute,
129
+ time.second,
130
+ microsecond=time.microsecond,
131
+ nanosecond=time.nanosecond % 1_000,
132
+ )
133
+
134
+ @property
135
+ def year(self) -> int:
136
+ """The year, e.g. 2026."""
137
+ return self._inner.year
138
+
139
+ @property
140
+ def month(self) -> int:
141
+ """The month, 1-12."""
142
+ return self._inner.month
143
+
144
+ @property
145
+ def day(self) -> int:
146
+ """The day of the month, 1-31."""
147
+ return self._inner.day
148
+
149
+ @property
150
+ def weekday(self) -> Weekday:
151
+ """The day of the week."""
152
+ return Weekday[self._inner.day_of_week().name]
153
+
154
+ def isoformat(self) -> str:
155
+ """Return the ISO 8601 form, e.g. ``"2026-01-15"``."""
156
+ return self._inner.format_iso()
157
+
158
+ def format(
159
+ self,
160
+ style: str = "medium",
161
+ locale: str | None = None,
162
+ pattern: str | None = None,
163
+ ) -> str:
164
+ """Format this date (see :func:`timecore.core._common._format_value`).
165
+
166
+ ``style`` is one of ``"short"``, ``"medium"``, ``"long"``,
167
+ ``"full"``; ``pattern`` is a Babel pattern. The default call
168
+ returns Babel's ``"medium"`` style output.
169
+ """
170
+ return _format_value(self, style=style, locale=locale, pattern=pattern)
171
+
172
+ def add(self, period: Period) -> Date:
173
+ """Return this date shifted by ``period``.
174
+
175
+ Raises:
176
+ ValueError: If ``period`` has a nonzero time component.
177
+ """
178
+ period = _require_instance(period, Period, "Date.add()")
179
+ if (
180
+ period.hours
181
+ or period.minutes
182
+ or period.seconds
183
+ or period.milliseconds
184
+ or period.microseconds
185
+ or period.nanoseconds
186
+ ):
187
+ raise ValueError(
188
+ f"cannot apply {period} to a Date: it has a nonzero time component"
189
+ )
190
+ with _map_whenever_errors():
191
+ return Date.from_whenever(
192
+ self._inner.add(
193
+ years=period.years,
194
+ months=period.months,
195
+ weeks=period.weeks,
196
+ days=period.days,
197
+ )
198
+ )
199
+
200
+ def __add__(self, other: object) -> Date:
201
+ if isinstance(other, Period):
202
+ return self.add(other)
203
+ if isinstance(other, Duration):
204
+ days = _require_whole_days(other)
205
+ with _map_whenever_errors():
206
+ return Date.from_whenever(self._inner.add(days=days))
207
+ return NotImplemented
208
+
209
+ def __radd__(self, other: object) -> Date:
210
+ return self.__add__(other)
211
+
212
+ def __sub__(self, other: object) -> Date | Period:
213
+ if isinstance(other, Period):
214
+ return self.add(-other)
215
+ if isinstance(other, Duration):
216
+ days = _require_whole_days(other)
217
+ with _map_whenever_errors():
218
+ return Date.from_whenever(self._inner.add(days=-days))
219
+ if isinstance(other, Date):
220
+ with _map_whenever_errors():
221
+ delta = self._inner.since(other._inner, in_units=["days"])
222
+ return Period(days=delta.get("days") or 0)
223
+ return NotImplemented
224
+
225
+ def __eq__(self, other: object) -> bool:
226
+ if isinstance(other, Date):
227
+ return self._inner == other._inner
228
+ return NotImplemented
229
+
230
+ def __lt__(self, other: object) -> bool:
231
+ if isinstance(other, Date):
232
+ return self._inner < other._inner
233
+ return NotImplemented
234
+
235
+ def __le__(self, other: object) -> bool:
236
+ if isinstance(other, Date):
237
+ return self._inner <= other._inner
238
+ return NotImplemented
239
+
240
+ def __gt__(self, other: object) -> bool:
241
+ if isinstance(other, Date):
242
+ return self._inner > other._inner
243
+ return NotImplemented
244
+
245
+ def __ge__(self, other: object) -> bool:
246
+ if isinstance(other, Date):
247
+ return self._inner >= other._inner
248
+ return NotImplemented
249
+
250
+ def __hash__(self) -> int:
251
+ return hash(self._inner)
252
+
253
+ def __repr__(self) -> str:
254
+ return f"Date({self.year}, {self.month}, {self.day})"
255
+
256
+ def __str__(self) -> str:
257
+ return self.isoformat()
@@ -0,0 +1,264 @@
1
+ """Duration: an exact amount of time.
2
+
3
+ A :class:`Duration` is a precise, calendar-independent length of time:
4
+ 2 hours 30 minutes is always exactly 9,000 seconds, wherever it is
5
+ applied. Days and weeks are exact multiples of 24 and 168 hours. For
6
+ calendar-based amounts (1 month, 1 year -- whose length depends on the
7
+ date), see :class:`~timecore.core.Period`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import timedelta as _StdTimedelta
13
+ from typing import ClassVar
14
+
15
+ import whenever
16
+
17
+ from ..errors import ParseError
18
+ from ._common import (
19
+ _check_us_precision,
20
+ _map_whenever_errors,
21
+ _require_instance,
22
+ _require_str,
23
+ _split_subsecond,
24
+ )
25
+
26
+ __all__ = ["Duration"]
27
+
28
+
29
+ class Duration:
30
+ """An exact amount of time, with nanosecond precision.
31
+
32
+ Negative durations are allowed. Days and weeks are exact: one day
33
+ is always 24 hours, even across a DST transition (contrast
34
+ :class:`~timecore.core.Period`, whose days are calendar days).
35
+
36
+ Example:
37
+ >>> Duration(hours=2, minutes=30)
38
+ Duration(hours=2, minutes=30)
39
+ """
40
+
41
+ __slots__ = ("_inner",)
42
+
43
+ # The wrapped whenever value; declared here so pyright knows its type
44
+ # (``__init__`` alone does not establish it for every construction path).
45
+ _inner: whenever.TimeDelta
46
+
47
+ #: The zero duration.
48
+ ZERO: ClassVar[Duration]
49
+
50
+ def __init__(
51
+ self,
52
+ days: float = 0,
53
+ hours: float = 0,
54
+ minutes: float = 0,
55
+ seconds: float = 0,
56
+ milliseconds: float = 0,
57
+ microseconds: float = 0,
58
+ nanoseconds: float = 0,
59
+ weeks: float = 0,
60
+ ) -> None:
61
+ # Days and weeks are converted to hours up front: passing them
62
+ # to whenever would treat them as exact 24-hour periods and emit
63
+ # a DaysAssumed24HoursWarning, and a Duration *is* exact time.
64
+ hours = hours + (weeks * 7 + days) * 24
65
+ with _map_whenever_errors():
66
+ # whenever types every component but nanoseconds as float;
67
+ # a float nanosecond count is truncated toward zero, matching
68
+ # whenever's own float handling.
69
+ self._inner = whenever.TimeDelta(
70
+ hours=hours,
71
+ minutes=minutes,
72
+ seconds=seconds,
73
+ milliseconds=milliseconds,
74
+ microseconds=microseconds,
75
+ nanoseconds=int(nanoseconds),
76
+ )
77
+
78
+ @classmethod
79
+ def from_whenever(cls, inner: whenever.TimeDelta) -> Duration:
80
+ """Wrap a whenever ``TimeDelta``.
81
+
82
+ Internal constructor; not part of the public API.
83
+ """
84
+ obj = cls.__new__(cls)
85
+ obj._inner = inner
86
+ return obj
87
+
88
+ @classmethod
89
+ def parse(cls, text: str) -> Duration:
90
+ """Parse an ISO 8601 duration such as ``"PT2H30M"`` or ``"P1D"``.
91
+
92
+ Raises:
93
+ ParseError: If ``text`` is not a valid ISO 8601 duration, or
94
+ if it has a years or months component, which cannot be
95
+ represented as an exact duration.
96
+ """
97
+ text = _require_str(text, "Duration.parse()")
98
+ try:
99
+ return cls.from_whenever(whenever.TimeDelta.parse_iso(text))
100
+ except ValueError:
101
+ pass
102
+ # whenever's TimeDelta parser rejects any date part, so handle
103
+ # day/week-based durations (and negative / mixed forms such as
104
+ # "P1DT2H") via the itemized parser.
105
+ try:
106
+ delta = whenever.ItemizedDelta.parse_iso(text)
107
+ except ValueError as exc:
108
+ raise ParseError(
109
+ f"could not parse {text!r} as an ISO 8601 duration"
110
+ ) from exc
111
+ years = delta.get("years") or 0
112
+ months = delta.get("months") or 0
113
+ if years or months:
114
+ raise ParseError(
115
+ f"could not parse {text!r} as an ISO 8601 duration: "
116
+ "years and months cannot be represented as an exact Duration"
117
+ )
118
+ milliseconds, microseconds, nanoseconds = _split_subsecond(
119
+ delta.get("nanoseconds") or 0
120
+ )
121
+ return cls(
122
+ days=(delta.get("days") or 0) + 7 * (delta.get("weeks") or 0),
123
+ hours=delta.get("hours") or 0,
124
+ minutes=delta.get("minutes") or 0,
125
+ seconds=delta.get("seconds") or 0,
126
+ milliseconds=milliseconds,
127
+ microseconds=microseconds,
128
+ nanoseconds=nanoseconds,
129
+ )
130
+
131
+ @classmethod
132
+ def from_timedelta(cls, value: _StdTimedelta) -> Duration:
133
+ """Create a :class:`Duration` from a standard-library ``timedelta``."""
134
+ value = _require_instance(value, _StdTimedelta, "Duration.from_timedelta()")
135
+ with _map_whenever_errors():
136
+ return cls.from_whenever(whenever.TimeDelta(value))
137
+
138
+ def to_timedelta(self) -> _StdTimedelta:
139
+ """Convert to a standard-library ``timedelta``.
140
+
141
+ Raises:
142
+ ValueError: If this duration has a sub-microsecond remainder,
143
+ which a ``timedelta`` cannot represent.
144
+ """
145
+ _check_us_precision(self.total_nanoseconds(), "Duration")
146
+ return self._inner.to_stdlib()
147
+
148
+ def total_nanoseconds(self) -> int:
149
+ """Return the total length of this duration in nanoseconds."""
150
+ return int(self._inner.total("nanoseconds"))
151
+
152
+ def total_seconds(self) -> float:
153
+ """Return the total length of this duration in seconds."""
154
+ return float(self._inner.total("seconds"))
155
+
156
+ def __add__(self, other: object) -> Duration:
157
+ if isinstance(other, Duration):
158
+ return Duration.from_whenever(self._inner + other._inner)
159
+ return NotImplemented
160
+
161
+ def __radd__(self, other: object) -> Duration:
162
+ return self.__add__(other)
163
+
164
+ def __sub__(self, other: object) -> Duration:
165
+ if isinstance(other, Duration):
166
+ return Duration.from_whenever(self._inner - other._inner)
167
+ return NotImplemented
168
+
169
+ def __rsub__(self, other: object) -> Duration:
170
+ if isinstance(other, Duration):
171
+ return Duration.from_whenever(other._inner - self._inner)
172
+ return NotImplemented
173
+
174
+ def __mul__(self, other: object) -> Duration:
175
+ if isinstance(other, (int, float)):
176
+ return Duration.from_whenever(self._inner * other)
177
+ return NotImplemented
178
+
179
+ def __rmul__(self, other: object) -> Duration:
180
+ return self.__mul__(other)
181
+
182
+ def __truediv__(self, other: object) -> Duration | float:
183
+ if isinstance(other, Duration):
184
+ if other._inner == whenever.TimeDelta():
185
+ raise ZeroDivisionError("division by a zero Duration")
186
+ return self._inner / other._inner
187
+ if isinstance(other, (int, float)):
188
+ return Duration.from_whenever(self._inner / other)
189
+ return NotImplemented
190
+
191
+ def __neg__(self) -> Duration:
192
+ return Duration.from_whenever(-self._inner)
193
+
194
+ def __pos__(self) -> Duration:
195
+ return Duration.from_whenever(+self._inner)
196
+
197
+ def __abs__(self) -> Duration:
198
+ return Duration.from_whenever(abs(self._inner))
199
+
200
+ def __eq__(self, other: object) -> bool:
201
+ if isinstance(other, Duration):
202
+ return self._inner == other._inner
203
+ return NotImplemented
204
+
205
+ def __lt__(self, other: object) -> bool:
206
+ if isinstance(other, Duration):
207
+ return self._inner < other._inner
208
+ return NotImplemented
209
+
210
+ def __le__(self, other: object) -> bool:
211
+ if isinstance(other, Duration):
212
+ return self._inner <= other._inner
213
+ return NotImplemented
214
+
215
+ def __gt__(self, other: object) -> bool:
216
+ if isinstance(other, Duration):
217
+ return self._inner > other._inner
218
+ return NotImplemented
219
+
220
+ def __ge__(self, other: object) -> bool:
221
+ if isinstance(other, Duration):
222
+ return self._inner >= other._inner
223
+ return NotImplemented
224
+
225
+ def __hash__(self) -> int:
226
+ return hash(self._inner)
227
+
228
+ def __bool__(self) -> bool:
229
+ return bool(self._inner)
230
+
231
+ def __repr__(self) -> str:
232
+ total_ns = self.total_nanoseconds()
233
+ if total_ns == 0:
234
+ return "Duration()"
235
+ sign = -1 if total_ns < 0 else 1
236
+ remaining = abs(total_ns)
237
+ days, remaining = divmod(remaining, 86_400_000_000_000)
238
+ hours, remaining = divmod(remaining, 3_600_000_000_000)
239
+ minutes, remaining = divmod(remaining, 60_000_000_000)
240
+ seconds, remaining = divmod(remaining, 1_000_000_000)
241
+ milliseconds, remaining = divmod(remaining, 1_000_000)
242
+ microseconds, nanoseconds = divmod(remaining, 1_000)
243
+ parts = [
244
+ (name, sign * value)
245
+ for name, value in [
246
+ ("days", days),
247
+ ("hours", hours),
248
+ ("minutes", minutes),
249
+ ("seconds", seconds),
250
+ ("milliseconds", milliseconds),
251
+ ("microseconds", microseconds),
252
+ ("nanoseconds", nanoseconds),
253
+ ]
254
+ if value
255
+ ]
256
+ inner = ", ".join(f"{name}={value}" for name, value in parts)
257
+ return f"Duration({inner})"
258
+
259
+ def __str__(self) -> str:
260
+ """Return the ISO 8601 form, e.g. ``"PT2H30M"``."""
261
+ return self._inner.format_iso()
262
+
263
+
264
+ Duration.ZERO = Duration()