diff --git a/src/pendulum/__init__.py b/src/pendulum/__init__.py index 16ae0865..6d1b304b 100644 --- a/src/pendulum/__init__.py +++ b/src/pendulum/__init__.py @@ -282,11 +282,16 @@ def from_format( return datetime(**parts) -def from_timestamp(timestamp: int | float, tz: str | Timezone = UTC) -> DateTime: +def from_timestamp(timestamp: float, tz: str | Timezone = UTC) -> DateTime: """ Create a DateTime instance from a timestamp. """ - dt = _datetime.datetime.fromtimestamp(timestamp, tz=UTC) + # datetime.fromtimestamp() delegates to the platform C library, which + # rejects negative timestamps on Windows. Use epoch arithmetic instead so + # all timestamps within datetime's range work consistently everywhere. + dt = _datetime.datetime( + 1970, 1, 1, tzinfo=_datetime.timezone.utc + ) + _datetime.timedelta(seconds=timestamp) dt = datetime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond diff --git a/tests/datetime/test_create_from_timestamp.py b/tests/datetime/test_create_from_timestamp.py index 121a7c29..a7f15d88 100644 --- a/tests/datetime/test_create_from_timestamp.py +++ b/tests/datetime/test_create_from_timestamp.py @@ -12,6 +12,12 @@ def test_create_from_timestamp_returns_pendulum(): assert d.timezone_name == "UTC" +def test_create_from_timestamp_before_epoch(): + d = pendulum.from_timestamp(-43201) + assert_datetime(d, 1969, 12, 31, 11, 59, 59) + assert d.timezone_name == "UTC" + + def test_create_from_timestamp_with_timezone_string(): d = pendulum.from_timestamp(0, "America/Toronto") assert d.timezone_name == "America/Toronto"