From c8c60e02eaf5febc25d4fb86635d2f48c8776c63 Mon Sep 17 00:00:00 2001 From: Peter Killick Date: Fri, 10 Feb 2017 10:27:15 +0000 Subject: [PATCH] Gracefully handle long time intervals --- lib/iris/coords.py | 8 +++++++- lib/iris/tests/unit/coords/test_Coord.py | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/iris/coords.py b/lib/iris/coords.py index c1686f90219..c4dab0fabe8 100644 --- a/lib/iris/coords.py +++ b/lib/iris/coords.py @@ -732,7 +732,13 @@ def __str__(self): fmt = '{cls}({points}{bounds}' \ ', standard_name={self.standard_name!r}' \ ', calendar={self.units.calendar!r}{other_metadata})' - points = self._str_dates(self.points) + if self.units.is_long_time_interval(): + # A time unit with a long time interval ("months" or "years") + # cannot be converted to a date using `num2date` so gracefully + # fall back to printing points as numbers, not datetimes. + points = self.points + else: + points = self._str_dates(self.points) bounds = '' if self.has_bounds(): bounds = ', bounds=' + self._str_dates(self.bounds) diff --git a/lib/iris/tests/unit/coords/test_Coord.py b/lib/iris/tests/unit/coords/test_Coord.py index bc3c4e3a656..779438170e2 100644 --- a/lib/iris/tests/unit/coords/test_Coord.py +++ b/lib/iris/tests/unit/coords/test_Coord.py @@ -323,5 +323,29 @@ def test_convert_unknown_units(self): with self.assertRaisesRegexp(UnitConversionError, emsg): coord.convert_units('degrees') +class Test___str__(tests.IrisTest): + + def test_short_time_interval(self): + coord = DimCoord([5], standard_name='time', + units='days since 1970-01-01') + expected = ("DimCoord([1970-01-06 00:00:00], standard_name='time', " + "calendar='gregorian')") + result = coord.__str__() + self.assertEqual(expected, result) + + def test_long_time_interval(self): + coord = DimCoord([5], standard_name='time', + units='years since 1970-01-01') + expected = "DimCoord([5], standard_name='time', calendar='gregorian')" + result = coord.__str__() + self.assertEqual(expected, result) + + def test_non_time_unit(self): + coord = DimCoord([1.]) + expected = repr(coord) + result = coord.__str__() + self.assertEqual(expected, result) + + if __name__ == '__main__': tests.main()