Skip to content

Commit 3873bc9

Browse files
authored
Merge pull request #392 from ocefpaf/handle_npdt64
Convert np.datetime64 to pydatetime
2 parents d429353 + 4643f62 commit 3873bc9

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/cftime/_cftime.pyx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,11 @@ def date2num(dates, units, calendar=None, has_year_zero=None, longdouble=False):
209209
mask = dates.mask
210210
ismasked = True
211211

212+
# Convert numpy.datetime64 to a list to convert them to datetime instances.
213+
if hasattr(dates, "dtype"):
214+
if np.issubdtype(dates.dtype, np.datetime64):
215+
dates = dates.tolist()
216+
212217
# are all input dates 'real' python datetime objects?
213218
dates = np.asanyarray(dates) # convert to numpy array
214219
shape = dates.shape # save shape of input

test/test_cftime.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2170,6 +2170,22 @@ def test_date2num_missing_data():
21702170
assert out is np.ma.masked
21712171

21722172

2173+
def test_date2num_numpy_datetime64():
2174+
# Array
2175+
array = np.array([
2176+
np.datetime64(123, "s"),
2177+
np.datetime64(124, "s"),
2178+
np.datetime64(125, "s")
2179+
])
2180+
out = date2num(array, units="seconds since 1970-01-01T00:00:00", calendar="gregorian")
2181+
assert ((out == np.array([123, 124, 125]))).all()
2182+
2183+
# Scalar
2184+
array = np.datetime64(123, "s")
2185+
out = date2num(array, units="seconds since 1970-01-01T00:00:00", calendar="gregorian")
2186+
assert out == np.int64(123)
2187+
2188+
21732189
def test_num2date_preserves_shape():
21742190
# The optimized num2date algorithm operates on a flattened array. This
21752191
# check ensures that the original shape of the times is restored in the

0 commit comments

Comments
 (0)