Skip to content
Prev Previous commit
Next Next commit
refactoring: inline a constant
  • Loading branch information
sblondon committed Dec 5, 2022
commit f709beb128c4d3c5f1f57d1399c9c3da9afe2764
3 changes: 2 additions & 1 deletion msgpack/ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ def to_datetime(self):

:rtype: datetime.
"""
return datetime.datetime.fromtimestamp(0, _utc) + datetime.timedelta(
utc = datetime.timezone.utc
return datetime.datetime.fromtimestamp(0, utc) + datetime.timedelta(
seconds=self.to_unix()
)

Expand Down
20 changes: 13 additions & 7 deletions test/test_timestamp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import sys
import datetime
import msgpack
from msgpack.ext import Timestamp, _utc
from msgpack.ext import Timestamp


def test_timestamp():
Expand Down Expand Up @@ -84,18 +84,21 @@ def test_timestamp_to():

def test_timestamp_datetime():
t = Timestamp(42, 14)
assert t.to_datetime() == datetime.datetime(1970, 1, 1, 0, 0, 42, 0, tzinfo=_utc)
utc = datetime.timezone.utc
assert t.to_datetime() == datetime.datetime(1970, 1, 1, 0, 0, 42, 0, tzinfo=utc)


def test_unpack_datetime():
t = Timestamp(42, 14)
utc = datetime.timezone.utc
packed = msgpack.packb(t)
unpacked = msgpack.unpackb(packed, timestamp=3)
assert unpacked == datetime.datetime(1970, 1, 1, 0, 0, 42, 0, tzinfo=_utc)
assert unpacked == datetime.datetime(1970, 1, 1, 0, 0, 42, 0, tzinfo=utc)


def test_pack_unpack_before_epoch():
t_in = datetime.datetime(1960, 1, 1, tzinfo=_utc)
utc = datetime.timezone.utc
t_in = datetime.datetime(1960, 1, 1, tzinfo=utc)
packed = msgpack.packb(t_in, datetime=True)
unpacked = msgpack.unpackb(packed, timestamp=3)
assert unpacked == t_in
Expand All @@ -104,7 +107,8 @@ def test_pack_unpack_before_epoch():
def test_pack_datetime():
t = Timestamp(42, 14000)
dt = t.to_datetime()
assert dt == datetime.datetime(1970, 1, 1, 0, 0, 42, 14, tzinfo=_utc)
utc = datetime.timezone.utc
assert dt == datetime.datetime(1970, 1, 1, 0, 0, 42, 14, tzinfo=utc)

packed = msgpack.packb(dt, datetime=True)
packed2 = msgpack.packb(t)
Expand All @@ -126,7 +130,8 @@ def test_pack_datetime():

def test_issue451():
# https://github.com/msgpack/msgpack-python/issues/451
dt = datetime.datetime(2100, 1, 1, 1, 1, tzinfo=_utc)
utc = datetime.timezone.utc
dt = datetime.datetime(2100, 1, 1, 1, 1, tzinfo=utc)
packed = msgpack.packb(dt, datetime=True)
assert packed == b"\xd6\xff\xf4\x86eL"

Expand All @@ -143,7 +148,8 @@ def test_pack_datetime_without_tzinfo():
packed = msgpack.packb(dt, datetime=True, default=lambda x: None)
assert packed == msgpack.packb(None)

dt = datetime.datetime(1970, 1, 1, 0, 0, 42, 14, tzinfo=_utc)
utc = datetime.timezone.utc
dt = datetime.datetime(1970, 1, 1, 0, 0, 42, 14, tzinfo=utc)
packed = msgpack.packb(dt, datetime=True)
unpacked = msgpack.unpackb(packed, timestamp=3)
assert unpacked == dt