Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
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
8 changes: 7 additions & 1 deletion numpy/core/src/multiarray/datetime.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#include <numpy/arrayobject.h>
#include "numpy/npy_math.h"

#include "npy_config.h"
#include "npy_pycompat.h"
Expand Down Expand Up @@ -2570,9 +2571,14 @@ convert_pyobject_to_datetime(PyArray_DatetimeMetaData *meta, PyObject *obj,
/*
* With unsafe casting, convert unrecognized objects into NaT
* and with same_kind casting, convert None into NaT
* We now also allow NPY_NAN to be cast to NaT; if control flow
* reaches the npy_isnan() check, an obj that can't be cast to
* float of some kind will cause a -1 return from PyFloat_AsDouble
* and control flow continues to ValueError as usual
*/
if (casting == NPY_UNSAFE_CASTING ||
(obj == Py_None && casting == NPY_SAME_KIND_CASTING)) {
(obj == Py_None && casting == NPY_SAME_KIND_CASTING) ||
(npy_isnan(PyFloat_AsDouble(obj)) && casting == NPY_SAME_KIND_CASTING)) {
if (meta->base == NPY_FR_ERROR) {
meta->base = NPY_FR_GENERIC;
meta->num = 1;
Expand Down
19 changes: 19 additions & 0 deletions numpy/core/tests/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,25 @@ def test_compare_generic_nat(self):
assert_(np.datetime64('NaT') == np.datetime64('NaT', 'us'))
assert_(np.datetime64('NaT', 'us') == np.datetime64('NaT'))

@pytest.mark.parametrize("arr, ind", [
# the exact test case reported in the issue
(np.zeros(5, dtype="M8[s]"), 2),
# similar thing with generic datetime64
(np.zeros(5, dtype="M8"), 1),
# multidimensional non-zero NaN to NaT
(np.ones((5, 3), dtype="M8[us]"), [1, 1]),
# and for generic datetime64
(np.ones((5, 3), dtype="M8"), [2, 1]),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: indent the lines within the list

])
def test_nan_nat_casting(self, arr, ind):
# regression tests for gh-8780
if isinstance(ind, (list,)):
arr[ind[0], ind[1]] = np.nan
assert_equal(arr[ind[0], ind[1]], np.datetime64('NaT'))
else:
arr[ind] = np.nan
assert_equal(arr[ind], np.datetime64('NaT'))

def test_datetime_scalar_construction(self):
# Construct with different units
assert_equal(np.datetime64('1950-03-12', 'D'),
Expand Down