Skip to content

Commit

Permalink
Merge ea139f0 into 31c8b7d
Browse files Browse the repository at this point in the history
  • Loading branch information
lafrech committed Mar 7, 2019
2 parents 31c8b7d + ea139f0 commit d253f06
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
10 changes: 10 additions & 0 deletions tests/test_fields.py
Expand Up @@ -161,6 +161,11 @@ class MySchema(EmbeddedSchema):
with pytest.raises(ValidationError):
s.load({'a': "dummy"})

# Test DateTimeField rounds to milliseconds
s = MySchema()
data, _ = s.load({'a': datetime(2016, 8, 6, 12, 30, 30, 123456)})
assert data['a'].microsecond == 123000

def test_strictdatetime(self):

class MySchema(EmbeddedSchema):
Expand Down Expand Up @@ -215,6 +220,11 @@ class MySchema(EmbeddedSchema):
assert d.get('b') == datetime(2016, 8, 5, 22, 0)
assert d.get('c') == datetime(2016, 8, 6, tzinfo=tzoffset(None, 7200))

# Test StrictDateTimeField rounds to milliseconds
s = MySchema()
data, _ = s.load({'a': datetime(2016, 8, 6, 12, 30, 30, 123456)})
assert data['a'].microsecond == 123000

def test_dict(self):

class MySchema(Schema):
Expand Down
16 changes: 12 additions & 4 deletions umongo/fields.py
Expand Up @@ -193,8 +193,12 @@ class DateTimeField(BaseField, ma_fields.DateTime):

def _deserialize(self, value, attr, data):
if isinstance(value, datetime):
return value
return super()._deserialize(value, attr, data)
ret = value
else:
ret = super()._deserialize(value, attr, data)
# MongoDB stores datetimes with a millisecond precision.
# Don't keep more precision in the object than in the database.
return ret.replace(microsecond=round(ret.microsecond, -3))


class LocalDateTimeField(BaseField, ma_fields.LocalDateTime):
Expand Down Expand Up @@ -242,8 +246,12 @@ class StrictDateTimeField(BaseField, ma_bonus_fields.StrictDateTime):

def _deserialize(self, value, attr, data):
if isinstance(value, datetime):
return self._set_tz_awareness(value)
return super()._deserialize(value, attr, data)
ret = self._set_tz_awareness(value)
else:
ret = super()._deserialize(value, attr, data)
# MongoDB stores datetimes with a millisecond precision.
# Don't keep more precision in the object than in the database.
return ret.replace(microsecond=round(ret.microsecond, -3))

def _deserialize_from_mongo(self, value):
return self._set_tz_awareness(value)
Expand Down

0 comments on commit d253f06

Please sign in to comment.