Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Comments

Fix Timestamp.from_datetime returning wrong value for pre-epoch datetimes#662

Open
bysiber wants to merge 1 commit intomsgpack:main from
bysiber:fix/timestamp-from-datetime-pre-epoch
Open

Fix Timestamp.from_datetime returning wrong value for pre-epoch datetimes #662
bysiber wants to merge 1 commit intomsgpack:main from
bysiber:fix/timestamp-from-datetime-pre-epoch

Conversation

@bysiber
Copy link

@bysiber bysiber commented Feb 20, 2026

Timestamp.from_datetime() uses int(dt.timestamp()) to compute the seconds component, but int() truncates towards zero. For pre-epoch datetimes with non-zero microseconds, this produces the wrong value:

import datetime
dt = datetime.datetime(1969, 12, 31, 23, 59, 59, 500000, tzinfo=datetime.timezone.utc)
# dt.timestamp() == -0.5
# int(-0.5) == 0 (truncation towards zero)
# Expected: Timestamp(seconds=-1, nanoseconds=500000000)
# Actual: Timestamp(seconds=0, nanoseconds=500000000) <-- +0.5s instead of -0.5s!

The sign of the time gets flipped. from_unix() already handles this correctly using floor division (int(unix_sec // 1)). This change makes from_datetime() consistent.

ThomasWaldmann reacted with eyes emoji
int() truncates towards zero, so for pre-epoch datetimes with non-zero
microseconds the seconds component gets the wrong value. For example,
datetime(1969, 12, 31, 23, 59, 59, 500000, UTC) has timestamp -0.5,
but int(-0.5) == 0, producing Timestamp(0, 500000000) (+0.5s after
epoch) instead of Timestamp(-1, 500000000) (-0.5s before epoch).
Use floor division (// 1) instead, consistent with from_unix().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

1 participant

AltStyle によって変換されたページ (->オリジナル) /