Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/pendulum/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions tests/datetime/test_create_from_timestamp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down