Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cftime/_cftime.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions test/test_cftime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down