mirror of
https://github.com/msgpack/msgpack-python.git
synced 2025-10-24 14:23:19 +00:00
Avoid using floating points during timestamp-datetime conversions (#591)
This commit is contained in:
parent
9aedf8ed7f
commit
e77672200b
2 changed files with 19 additions and 2 deletions
|
|
@ -157,7 +157,9 @@ class Timestamp:
|
||||||
:rtype: `datetime.datetime`
|
:rtype: `datetime.datetime`
|
||||||
"""
|
"""
|
||||||
utc = datetime.timezone.utc
|
utc = datetime.timezone.utc
|
||||||
return datetime.datetime.fromtimestamp(0, utc) + datetime.timedelta(seconds=self.to_unix())
|
return datetime.datetime.fromtimestamp(0, utc) + datetime.timedelta(
|
||||||
|
seconds=self.seconds, microseconds=self.nanoseconds // 1000
|
||||||
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def from_datetime(dt):
|
def from_datetime(dt):
|
||||||
|
|
@ -165,4 +167,4 @@ class Timestamp:
|
||||||
|
|
||||||
:rtype: Timestamp
|
:rtype: Timestamp
|
||||||
"""
|
"""
|
||||||
return Timestamp.from_unix(dt.timestamp())
|
return Timestamp(seconds=int(dt.timestamp()), nanoseconds=dt.microsecond * 1000)
|
||||||
|
|
|
||||||
|
|
@ -86,6 +86,21 @@ def test_timestamp_datetime():
|
||||||
utc = datetime.timezone.utc
|
utc = datetime.timezone.utc
|
||||||
assert t.to_datetime() == datetime.datetime(1970, 1, 1, 0, 0, 42, 0, tzinfo=utc)
|
assert t.to_datetime() == datetime.datetime(1970, 1, 1, 0, 0, 42, 0, tzinfo=utc)
|
||||||
|
|
||||||
|
ts = datetime.datetime(2024, 4, 16, 8, 43, 9, 420317, tzinfo=utc)
|
||||||
|
ts2 = datetime.datetime(2024, 4, 16, 8, 43, 9, 420318, tzinfo=utc)
|
||||||
|
|
||||||
|
assert (
|
||||||
|
Timestamp.from_datetime(ts2).nanoseconds - Timestamp.from_datetime(ts).nanoseconds == 1000
|
||||||
|
)
|
||||||
|
|
||||||
|
ts3 = datetime.datetime(2024, 4, 16, 8, 43, 9, 4256)
|
||||||
|
ts4 = datetime.datetime(2024, 4, 16, 8, 43, 9, 4257)
|
||||||
|
assert (
|
||||||
|
Timestamp.from_datetime(ts4).nanoseconds - Timestamp.from_datetime(ts3).nanoseconds == 1000
|
||||||
|
)
|
||||||
|
|
||||||
|
assert Timestamp.from_datetime(ts).to_datetime() == ts
|
||||||
|
|
||||||
|
|
||||||
def test_unpack_datetime():
|
def test_unpack_datetime():
|
||||||
t = Timestamp(42, 14)
|
t = Timestamp(42, 14)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue