From ef3c46b5175fee7688047e7fadfe2b8c1a47cbd1 Mon Sep 17 00:00:00 2001 From: Jeff Whitaker Date: Mon, 29 Apr 2024 12:42:51 -0600 Subject: [PATCH] add test, Changelog entry --- Changelog | 1 + src/cftime/_cftime.pyx | 2 +- test/test_cftime.py | 13 +++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/Changelog b/Changelog index e9a7e854..f2962d6e 100644 --- a/Changelog +++ b/Changelog @@ -2,6 +2,7 @@ since version 1.6.3 release =========================== * build musllinux wheels (issue #307). * return empty array if one provided to date2num (issue #315). + * handle nan/inf in num2date (issue #328). version 1.6.3 (release tag v1.6.3rel) ===================================== diff --git a/src/cftime/_cftime.pyx b/src/cftime/_cftime.pyx index 6329a342..a33ad80c 100644 --- a/src/cftime/_cftime.pyx +++ b/src/cftime/_cftime.pyx @@ -621,7 +621,7 @@ def num2date( times = np.asanyarray(times) # Allow list as input times = upcast_times(times) # convert to masked array if any nan or inf values present - if not np.isfinite(times).any(): + if not np.isfinite(times).all(): times = np.ma.masked_invalid(times) scaled_times = scale_times(times, factor) scaled_times = cast_to_int(scaled_times,units=unit) diff --git a/test/test_cftime.py b/test/test_cftime.py index 8e9daae7..07d7c6e9 100644 --- a/test/test_cftime.py +++ b/test/test_cftime.py @@ -930,6 +930,19 @@ def roundtrip(delta,eps,units): # date2num should return an empty array if given one (issue #315) d = cftime.date2num([], 'seconds since 2000-01-01 12:00:00') assert d.size==0 + # issue #328: handle nan/inf in num2date. + times = np.array([1,2,3,np.nan],dtype=np.float64) + expected = np.array([DatetimeGregorian(2000, 1, 2, 0, 0, 0, 0), + DatetimeGregorian(2000, 1, 3, 0, 0, 0, 0), + DatetimeGregorian(2000, 1, 4, 0, 0, 0, 0), + DatetimeGregorian(2000, 1, 5, 0, 0, 0, 0)]) + mask = [False, False, False, True] + expected = np.ma.masked_array(expected, mask=mask) + result = cftime.num2date(times, 'days since 2000-01-01', 'standard') + np.testing.assert_equal(result, expected) + times = np.array([1,2,3,np.inf],dtype=np.float64) + result = cftime.num2date(times, 'days since 2000-01-01', 'standard') + np.testing.assert_equal(result, expected) class TestDate2index(unittest.TestCase):