diff --git a/oslo_serialization/jsonutils.py b/oslo_serialization/jsonutils.py index 69d746c..89b6862 100644 --- a/oslo_serialization/jsonutils.py +++ b/oslo_serialization/jsonutils.py @@ -43,6 +43,8 @@ from oslo_utils import encodeutils from oslo_utils import importutils from oslo_utils import timeutils +_ISO8601_DATE_FORMAT = '%Y-%m-%d' + ipaddress = importutils.try_import("ipaddress") netaddr = importutils.try_import("netaddr") @@ -117,6 +119,12 @@ def to_primitive(value, convert_instances=False, convert_datetime=True, else: return value + if isinstance(value, datetime.date): + if convert_datetime: + return value.strftime(_ISO8601_DATE_FORMAT) + else: + return value + if isinstance(value, uuid.UUID): return str(value) diff --git a/oslo_serialization/tests/test_jsonutils.py b/oslo_serialization/tests/test_jsonutils.py index 74289b9..d68b22c 100644 --- a/oslo_serialization/tests/test_jsonutils.py +++ b/oslo_serialization/tests/test_jsonutils.py @@ -159,6 +159,15 @@ class ToPrimitiveTestCase(test_base.BaseTestCase): x = datetime.datetime(1920, 2, 3, 4, 5, 6, 7) self.assertEqual(x, jsonutils.to_primitive(x, convert_datetime=False)) + def test_date(self): + x = datetime.date(1920, 2, 3) + self.assertEqual('1920-02-03', + jsonutils.to_primitive(x)) + + def test_date_preserve(self): + x = datetime.date(1920, 2, 3) + self.assertEqual(x, jsonutils.to_primitive(x, convert_datetime=False)) + def test_DateTime(self): x = xmlrpclib.DateTime() x.decode("19710203T04:05:06")