PYTHON-1603 Truncate large datetimes properly (#362)

This commit is contained in:
Shane Harvey 2018-07-09 16:28:48 -07:00 committed by Shane Harvey
parent 649ae04afe
commit b63442ace0
2 changed files with 9 additions and 2 deletions

View File

@ -819,7 +819,7 @@ if _USE_C:
def _millis_to_datetime(millis, opts):
"""Convert milliseconds since epoch UTC to datetime."""
diff = ((millis % 1000) + 1000) % 1000
seconds = (millis - diff) / 1000
seconds = (millis - diff) // 1000
micros = diff * 1000
if opts.tz_aware:
dt = EPOCH_AWARE + datetime.timedelta(seconds=seconds,
@ -837,7 +837,7 @@ def _datetime_to_millis(dtm):
if dtm.utcoffset() is not None:
dtm = dtm - dtm.utcoffset()
return int(calendar.timegm(dtm.timetuple()) * 1000 +
dtm.microsecond / 1000)
dtm.microsecond // 1000)
_CODEC_OPTIONS_TYPE_ERROR = TypeError(

View File

@ -474,6 +474,13 @@ class TestBSON(unittest.TestCase):
dt2 = BSON.encode({"date": dt1}).decode()["date"]
self.assertEqual(dt1, dt2)
def test_large_datetime_truncation(self):
# Ensure that a large datetime is truncated correctly.
dt1 = datetime.datetime(9999, 1, 1, 1, 1, 1, 999999)
dt2 = BSON.encode({"date": dt1}).decode()["date"]
self.assertEqual(dt2.microsecond, 999000)
self.assertEqual(dt2.second, dt1.second)
def test_aware_datetime(self):
aware = datetime.datetime(1993, 4, 4, 2,
tzinfo=FixedOffset(555, "SomeZone"))