diff --git a/src/cftime/_cftime.pyx b/src/cftime/_cftime.pyx index 15d7fb66..93b46c5c 100644 --- a/src/cftime/_cftime.pyx +++ b/src/cftime/_cftime.pyx @@ -209,6 +209,11 @@ def date2num(dates, units, calendar=None, has_year_zero=None, longdouble=False): mask = dates.mask ismasked = True + # Convert numpy.datetime64 to a list to convert them to datetime instances. + if hasattr(dates, "dtype"): + if np.issubdtype(dates.dtype, np.datetime64): + dates = dates.tolist() + # are all input dates 'real' python datetime objects? dates = np.asanyarray(dates) # convert to numpy array shape = dates.shape # save shape of input diff --git a/test/test_cftime.py b/test/test_cftime.py index ff91ae4b..33e1c622 100644 --- a/test/test_cftime.py +++ b/test/test_cftime.py @@ -2170,6 +2170,22 @@ def test_date2num_missing_data(): assert out is np.ma.masked +def test_date2num_numpy_datetime64(): + # Array + array = np.array([ + np.datetime64(123, "s"), + np.datetime64(124, "s"), + np.datetime64(125, "s") + ]) + out = date2num(array, units="seconds since 1970-01-01T00:00:00", calendar="gregorian") + assert ((out == np.array([123, 124, 125]))).all() + + # Scalar + array = np.datetime64(123, "s") + out = date2num(array, units="seconds since 1970-01-01T00:00:00", calendar="gregorian") + assert out == np.int64(123) + + def test_num2date_preserves_shape(): # The optimized num2date algorithm operates on a flattened array. This # check ensures that the original shape of the times is restored in the