Skip to content

Commit

Permalink
Handle masked arrays in num2date
Browse files Browse the repository at this point in the history
  • Loading branch information
djkirkham committed Sep 15, 2016
1 parent 3f3301d commit e6f6ab1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
8 changes: 4 additions & 4 deletions cf_units/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit e6f6ab1

Please sign in to comment.