From e6f6ab1db7ef581d0b7c5fd2a58bc6275e3aac57 Mon Sep 17 00:00:00 2001 From: Daniel Kirkham Date: Thu, 15 Sep 2016 15:24:09 +0100 Subject: [PATCH] Handle masked arrays in num2date --- cf_units/__init__.py | 8 ++++---- .../integration/test__num2date_to_nearest_second.py | 9 +++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/cf_units/__init__.py b/cf_units/__init__.py index 15bb6bb2..fc785906 100644 --- a/cf_units/__init__.py +++ b/cf_units/__init__.py @@ -712,8 +712,8 @@ def _discard_microsecond(date): # Create date objects of the same type returned by utime.num2date() # (either datetime.datetime or netcdftime.datetime), discarding the # microseconds - dates = np.array([d.__class__(d.year, d.month, d.day, - d.hour, d.minute, d.second) + dates = np.array([d and d.__class__(d.year, d.month, d.day, + d.hour, d.minute, d.second) for d in dates]) result = dates[0] if shape is () else dates.reshape(shape) return result @@ -802,7 +802,7 @@ def _num2date_to_nearest_second(time_value, utime): Returns: datetime, or numpy.ndarray of datetime object. """ - time_values = np.asarray(time_value) + time_values = np.asanyarray(time_value) shape = time_values.shape time_values = time_values.ravel() @@ -820,7 +820,7 @@ def _num2date_to_nearest_second(time_value, utime): dates = utime.num2date(time_values) try: # We can assume all or none of the dates have a microsecond attribute - microseconds = np.array([d.microsecond for d in dates]) + microseconds = np.array([d and d.microsecond for d in dates]) except AttributeError: microseconds = 0 round_mask = np.logical_or(has_half_seconds, microseconds != 0) diff --git a/cf_units/tests/integration/test__num2date_to_nearest_second.py b/cf_units/tests/integration/test__num2date_to_nearest_second.py index a80b3b41..cdf0871e 100644 --- a/cf_units/tests/integration/test__num2date_to_nearest_second.py +++ b/cf_units/tests/integration/test__num2date_to_nearest_second.py @@ -67,6 +67,15 @@ def test_multidim_sequence(self): res = _num2date_to_nearest_second(nums, utime) self.assertEqual(exp_shape, res.shape) + def test_masked_ndarray(self): + utime = netcdftime.utime('seconds since 1970-01-01', 'gregorian') + nums = np.ma.masked_array([20., 40., 60.], [False, True, False]) + exp = [datetime.datetime(1970, 1, 1, 0, 0, 20), + None, + datetime.datetime(1970, 1, 1, 0, 1)] + res = _num2date_to_nearest_second(nums, utime) + np.testing.assert_array_equal(exp, res) + # Gregorian Calendar tests def test_simple_gregorian(self):