From dcaa3f8921630a9d8bb773c128d26de9376e8a08 Mon Sep 17 00:00:00 2001 From: abu-tahir-0 Date: Fri, 20 Nov 2026 17:41:04 +0530 Subject: [PATCH] fix: support negative timestamps in from_timestamp on Windows datetime.fromtimestamp() delegates to the platform C library and raises OSError on Windows for timestamps before 1969-12-31 12:00:00 UTC, even though those dates are well within datetime's range. Compute the UTC value with epoch arithmetic instead, which is portable and handles all supported timestamps consistently. Add a regression test. --- src/pendulum/__init__.py | 9 +++++++-- tests/datetime/test_create_from_timestamp.py | 6 ++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/pendulum/__init__.py b/src/pendulum/__init__.py index 16ae0865c..6d1b304b9 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 121a7c294..a7f15d888 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"