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,249 @@
1
+ """Locale-aware formatting of temporal values, backed by Babel.
2
+
3
+ Babel is an implementation detail: no Babel type or exception ever
4
+ escapes this module. An unknown locale raises
5
+ :class:`~timecore.errors.InvalidLocaleError`; an invalid style, or a
6
+ pattern Babel cannot apply to the value, raises ``ValueError``.
7
+
8
+ ``Period`` intentionally has no locale-aware formatting in v0.1.0:
9
+ its ``__str__`` stays ISO 8601.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from datetime import date as _StdDate
15
+ from datetime import datetime as _StdDateTime
16
+ from datetime import time as _StdTime
17
+ from datetime import timedelta as _StdTimedelta
18
+ from typing import cast
19
+
20
+ from babel import dates as _babel_dates
21
+ from babel.core import Locale as _BabelLocale
22
+ from babel.core import UnknownLocaleError as _UnknownLocaleError
23
+
24
+ from ..core import Date, DateTime, Duration, Instant, LocalDateTime, Time, TimeZone
25
+ from ..errors import InvalidLocaleError
26
+
27
+ __all__ = [
28
+ "format_duration",
29
+ "format_temporal",
30
+ ]
31
+
32
+ #: Valid ``style`` values for :func:`format_temporal`.
33
+ _FORMAT_STYLES = ("short", "medium", "long", "full")
34
+
35
+
36
+ def _validate_locale(locale: object) -> str | None:
37
+ """Return ``locale`` if it is None or a locale Babel knows, else raise.
38
+
39
+ Takes ``object`` so pyright does not flag the runtime type check as
40
+ unnecessary when callers already declare a ``str`` parameter; the
41
+ check still protects against wrongly typed callers at runtime.
42
+ """
43
+ if locale is None:
44
+ return None
45
+ if not isinstance(locale, str):
46
+ raise TypeError(f"locale must be a string, got {type(locale).__name__}")
47
+ try:
48
+ _BabelLocale.parse(locale)
49
+ except (_UnknownLocaleError, ValueError) as exc:
50
+ raise InvalidLocaleError(f"unknown locale {locale!r}") from exc
51
+ return locale
52
+
53
+
54
+ def _optional_str(value: object, what: str) -> str | None:
55
+ """Return ``value`` if it is None or a string, else raise ``TypeError``."""
56
+ if value is None or isinstance(value, str):
57
+ return value
58
+ raise TypeError(f"{what} must be a string, got {type(value).__name__}")
59
+
60
+
61
+ def _require_temporal(
62
+ value: object,
63
+ ) -> Date | Time | LocalDateTime | DateTime | Instant:
64
+ """Return ``value`` if it is a temporal value, else raise ``TypeError``."""
65
+ if not isinstance(value, (Date, Time, LocalDateTime, DateTime, Instant)):
66
+ raise TypeError(
67
+ "value must be a Date, Time, LocalDateTime, DateTime, or Instant, "
68
+ f"got {type(value).__name__}"
69
+ )
70
+ return value
71
+
72
+
73
+ def _require_duration(value: object) -> Duration:
74
+ """Return ``value`` if it is a Duration, else raise ``TypeError``."""
75
+ if not isinstance(value, Duration):
76
+ raise TypeError(f"duration must be a Duration, got {type(value).__name__}")
77
+ return value
78
+
79
+
80
+ def _validate_style(style: str) -> str:
81
+ """Return ``style`` if it is a known Babel format style, else raise ``ValueError``."""
82
+ if style not in _FORMAT_STYLES:
83
+ raise ValueError(
84
+ f"style must be one of 'short', 'medium', 'long', 'full', got {style!r}"
85
+ )
86
+ return style
87
+
88
+
89
+ def _truncated_time(value: Time) -> _StdTime:
90
+ """Convert ``value`` to a stdlib ``time``, truncating sub-microsecond precision.
91
+
92
+ Formatting displays at most microseconds, so a nanosecond remainder
93
+ is dropped here rather than rejecting the value: this is display
94
+ precision, not a lossy conversion of the value itself.
95
+ """
96
+ return _StdTime(value.hour, value.minute, value.second, value.microsecond)
97
+
98
+
99
+ def _truncated_datetime(value: LocalDateTime | DateTime) -> _StdDateTime:
100
+ """Convert ``value`` to a stdlib ``datetime``, truncating sub-microsecond precision."""
101
+ naive = _StdDateTime(
102
+ value.year,
103
+ value.month,
104
+ value.day,
105
+ value.hour,
106
+ value.minute,
107
+ value.second,
108
+ value.microsecond,
109
+ )
110
+ if isinstance(value, DateTime):
111
+ return naive.replace(tzinfo=value.timezone.to_zoneinfo())
112
+ return naive
113
+
114
+
115
+ def _to_stdlib(
116
+ value: Date | Time | LocalDateTime | DateTime | Instant,
117
+ timezone: TimeZone | str | None,
118
+ ) -> _StdDate | _StdTime | _StdDateTime:
119
+ """Convert ``value`` to the stdlib object Babel formats.
120
+
121
+ An ``Instant`` becomes an aware stdlib ``datetime`` in ``timezone``
122
+ (UTC when ``timezone`` is None); every other type converts directly.
123
+ Values with sub-microsecond precision are truncated to microseconds
124
+ for display (see :func:`_truncated_time`).
125
+ """
126
+ if isinstance(value, Date):
127
+ return value.to_date()
128
+ if isinstance(value, Time):
129
+ try:
130
+ return value.to_time()
131
+ except ValueError:
132
+ return _truncated_time(value)
133
+ if isinstance(value, LocalDateTime):
134
+ try:
135
+ return value.to_datetime()
136
+ except ValueError:
137
+ return _truncated_datetime(value)
138
+ if isinstance(value, DateTime):
139
+ try:
140
+ return value.to_datetime()
141
+ except ValueError:
142
+ return _truncated_datetime(value)
143
+ # Instant: resolve to a DateTime in the requested zone first, so the
144
+ # wall time Babel sees is the one in that zone (UTC by default).
145
+ zoned = value.to_datetime(timezone if timezone is not None else "UTC")
146
+ try:
147
+ return zoned.to_datetime()
148
+ except ValueError:
149
+ return _truncated_datetime(zoned)
150
+
151
+
152
+ def format_temporal(
153
+ value: Date | Time | LocalDateTime | DateTime | Instant,
154
+ *,
155
+ style: str = "medium",
156
+ locale: str | None = None,
157
+ pattern: str | None = None,
158
+ timezone: TimeZone | str | None = None,
159
+ ) -> str:
160
+ """Format a temporal value for display, using Babel.
161
+
162
+ Args:
163
+ value: The value to format: a :class:`~timecore.core.Date`,
164
+ :class:`~timecore.core.Time`,
165
+ :class:`~timecore.core.LocalDateTime`,
166
+ :class:`~timecore.core.DateTime`, or
167
+ :class:`~timecore.core.Instant`.
168
+ style: One of ``"short"``, ``"medium"``, ``"long"``, ``"full"``
169
+ (default ``"medium"``). Ignored when ``pattern`` is given.
170
+ locale: A Babel locale such as ``"en_US"`` or ``"zh_TW"``.
171
+ ``None`` uses Babel's default locale.
172
+ pattern: A Babel date/time pattern string, e.g. ``"yyyy-MM-dd"``.
173
+ Takes precedence over ``style``.
174
+ timezone: Only applies to an ``Instant``: the zone the instant
175
+ is shown in (a :class:`~timecore.core.TimeZone` or key).
176
+ An instant formats in UTC unless a timezone is given.
177
+
178
+ Returns:
179
+ The formatted string, e.g. ``Date(2026, 1, 15)`` with
180
+ ``locale="en_US"`` formats as ``"Jan 15, 2026"`` (medium style).
181
+
182
+ Raises:
183
+ TypeError: If ``value`` is not a temporal value, or ``locale`` /
184
+ ``pattern`` is not a string.
185
+ ValueError: If ``style`` is unknown, ``pattern`` cannot be
186
+ applied to ``value``, or ``timezone`` is given for a value
187
+ that is not an ``Instant``.
188
+ InvalidLocaleError: If ``locale`` is not a known locale.
189
+ """
190
+ value = _require_temporal(value)
191
+ _validate_style(style)
192
+ locale = _validate_locale(locale)
193
+ pattern = _optional_str(pattern, "pattern")
194
+ if timezone is not None and not isinstance(value, Instant):
195
+ raise ValueError("timezone only applies when formatting an Instant")
196
+ stdlib_value = _to_stdlib(value, timezone)
197
+ fmt = pattern if pattern is not None else style
198
+ try:
199
+ if isinstance(stdlib_value, _StdDateTime):
200
+ return _babel_dates.format_datetime(stdlib_value, format=fmt, locale=locale)
201
+ if isinstance(stdlib_value, _StdDate):
202
+ return _babel_dates.format_date(stdlib_value, format=fmt, locale=locale)
203
+ return _babel_dates.format_time(stdlib_value, format=fmt, locale=locale)
204
+ except Exception as exc:
205
+ raise ValueError(
206
+ f"cannot format {value!r} with "
207
+ + (f"pattern {pattern!r}" if pattern is not None else f"style {style!r}")
208
+ + f": {exc}"
209
+ ) from exc
210
+
211
+
212
+ def format_duration(duration: Duration, *, locale: str | None = None) -> str:
213
+ """Format a duration for display, using Babel's ``format_timedelta``.
214
+
215
+ Args:
216
+ duration: The :class:`~timecore.core.Duration` to format.
217
+ locale: A Babel locale such as ``"en_US"`` or ``"zh_TW"``.
218
+ ``None`` uses Babel's default locale.
219
+
220
+ Returns:
221
+ The formatted string, e.g. ``Duration(hours=2, minutes=30)``
222
+ with ``locale="en_US"`` formats as ``"2 hours"`` (Babel picks
223
+ the largest fitting unit). A zero duration formats as
224
+ ``"0 seconds"``. Babel formats the magnitude of a negative
225
+ duration, without a sign: ``Duration(hours=-2)`` formats as
226
+ ``"2 hours"``.
227
+
228
+ Raises:
229
+ TypeError: If ``duration`` is not a :class:`~timecore.core.Duration`,
230
+ or ``locale`` is not a string.
231
+ InvalidLocaleError: If ``locale`` is not a known locale.
232
+ """
233
+ duration = _require_duration(duration)
234
+ locale = _validate_locale(locale)
235
+ try:
236
+ delta = duration.to_timedelta()
237
+ except (ValueError, OverflowError):
238
+ # Sub-microsecond precision (or a range beyond timedelta) cannot
239
+ # be a stdlib timedelta; fall back to seconds as a float, which
240
+ # Babel accepts at runtime (its type stub only declares
241
+ # ``timedelta | int``). Display granularity is seconds or
242
+ # coarser, so nothing visible is lost.
243
+ delta = duration.total_seconds()
244
+ try:
245
+ return _babel_dates.format_timedelta(
246
+ cast("_StdTimedelta | int", delta), locale=locale
247
+ )
248
+ except Exception as exc:
249
+ raise ValueError(f"cannot format duration {duration!r}: {exc}") from exc
@@ -0,0 +1,8 @@
1
+ """Intervals and interval sets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .interval import Endpoint, Interval
6
+ from .interval_set import IntervalSet
7
+
8
+ __all__ = ["Endpoint", "Interval", "IntervalSet"]