diff --git a/_python_utils_tests/test_time.py b/_python_utils_tests/test_time.py index b30d7c5..8747027 100644 --- a/_python_utils_tests/test_time.py +++ b/_python_utils_tests/test_time.py @@ -4,6 +4,7 @@ import datetime import itertools import time +from types import SimpleNamespace import pytest @@ -465,6 +466,75 @@ def test_format_time_extreme_timedeltas() -> None: assert smallest == '-999999999 days, 0:00:00' +@pytest.mark.parametrize( + 'value,precision,expected', + [ + ( + datetime.datetime(1960, 1, 2, 3, 4, 5, 678901), + datetime.timedelta(seconds=1), + '1960-01-02 03:04:05', + ), + ( + datetime.datetime(1900, 1, 2, 3, 4, 5, 678901), + datetime.timedelta(milliseconds=10), + '1900-01-02 03:04:05.670000', + ), + ( + datetime.datetime.min, + datetime.timedelta(seconds=1), + '0001-01-01 00:00:00', + ), + ( + datetime.datetime.max, + datetime.timedelta(seconds=1), + '9999-12-31 23:59:59', + ), + ], +) +def test_format_time_outside_platform_timestamp_range( + value: datetime.datetime, + precision: datetime.timedelta, + expected: str, +) -> None: + """Format valid naive dates outside the platform's timestamp range.""" + assert python_utils.format_time(value, precision) == expected + + +@pytest.mark.parametrize('error', [OverflowError, OSError, ValueError]) +@pytest.mark.parametrize('tzinfo', [None, datetime.timezone.utc]) +def test_format_time_unavailable_fromtimestamp( + monkeypatch: pytest.MonkeyPatch, + error: type[Exception], + tzinfo: datetime.tzinfo | None, +) -> None: + """Handle platform conversion failures on systems with a wider range.""" + + class LimitedDatetime(datetime.datetime): + """Simulate a platform unable to convert the timestamp back.""" + + @classmethod + def fromtimestamp( + cls, timestamp: float, tz: datetime.tzinfo | None = None + ) -> 'LimitedDatetime': + """Reject dates outside the simulated platform range.""" + raise error('timestamp out of range') + + value = LimitedDatetime(2000, 1, 2, 3, 4, 5, 678901, tzinfo=tzinfo) + monkeypatch.setattr( + python_utils.time, + 'datetime', + SimpleNamespace( + datetime=LimitedDatetime, + timedelta=datetime.timedelta, + date=datetime.date, + ), + ) + expected = ( + '2000-01-02 03:04:05' if tzinfo is None else str(datetime.datetime.max) + ) + assert python_utils.format_time(value) == expected + + @pytest.mark.parametrize( 'delta', [ diff --git a/python_utils/time.py b/python_utils/time.py index f4fb5af..1fe0b26 100644 --- a/python_utils/time.py +++ b/python_utils/time.py @@ -110,6 +110,23 @@ def delta_to_seconds_or_none( return delta_to_seconds(interval) +def _format_datetime( + timestamp: datetime.datetime, precision: datetime.timedelta +) -> str: + """Format a datetime even outside the platform's timestamp range.""" + try: + since_epoch = datetime.timedelta(seconds=timestamp.timestamp()) + seconds = (since_epoch - since_epoch % precision).total_seconds() + return str(datetime.datetime.fromtimestamp(seconds)) + except (OverflowError, OSError, ValueError): + if timestamp.tzinfo is not None: + return str(datetime.datetime.max) + # Windows cannot convert pre-epoch naive dates to timestamps. + # Exact wall-clock arithmetic also handles the datetime bounds. + since_epoch = timestamp - epoch + return str(timestamp - since_epoch % precision) + + def format_time( timestamp: _aliases.timestamp_type, precision: datetime.timedelta = datetime.timedelta(seconds=1), @@ -124,6 +141,8 @@ def format_time( '0:00:01' >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6)) '2000-01-02 03:04:05' + >>> format_time(datetime.datetime(1900, 1, 2, 3, 4, 5)) + '1900-01-02 03:04:05' >>> format_time(datetime.date(2000, 1, 2)) '2000-01-02' >>> format_time(datetime.timedelta(seconds=3661)) @@ -152,23 +171,8 @@ def format_time( # whole microseconds, which keeps the modulo exact. In float seconds # `1.0 % 0.1` is just under 0.1 and the result drops a whole step. return str(timestamp - timestamp % precision) - elif isinstance(timestamp, datetime.datetime): # pragma: no cover - # Python 2 doesn't have the timestamp method - if hasattr(timestamp, 'timestamp'): - seconds = timestamp.timestamp() - else: - seconds = timedelta_to_seconds(timestamp - epoch) - - # Truncate the number to the given precision, in whole microseconds - # for the same reason as above - since_epoch: datetime.timedelta = datetime.timedelta(seconds=seconds) - seconds = (since_epoch - since_epoch % precision).total_seconds() - - try: # pragma: no cover - dt = datetime.datetime.fromtimestamp(seconds) - except (ValueError, OSError): # pragma: no cover - dt = datetime.datetime.max - return str(dt) + elif isinstance(timestamp, datetime.datetime): + return _format_datetime(timestamp, precision) elif isinstance(timestamp, datetime.date): return str(timestamp) elif timestamp is None: