## Numpy：如何检查某个值是否为NAT？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (77)
```nat = np.datetime64('NaT')
nat == nat
>> FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.

np.isnan(nat)
>> TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''```

### 2 个回答

```import numpy as np
nat = np.datetime64('NaT')

def nat_check(nat):
return nat == np.datetime64('NaT')

nat_check(nat)
Out[4]: FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
True

nat_check(nat)
Out[5]: True```

```import numpy as np
import warnings

nat = np.datetime64('NaT')

def nat_check(nat):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')

nat_check(nat)
Out[5]: True```

```def nat_check(nat):
if [int(x) for x in np.__version__.split('.')[:-1]] > [1, 11]:
return nat != nat
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')```

pandas可以检查`NaT，使用``pandas.isnull`:

```>>> import numpy as np
>>> import pandas as pd
>>> pd.isnull(np.datetime64('NaT'))
True```

```nat_as_integer = np.datetime64('NAT').view('i8')

def isnat(your_datetime):
dtype_string = str(your_datetime.dtype)
if 'datetime64' in dtype_string or 'timedelta64' in dtype_string:
return your_datetime.view('i8') == nat_as_integer
return False  # it can't be a NaT if it's not a dateime```

```>>> isnat(np.datetime64('NAT'))
True

>>> isnat(np.timedelta64('NAT'))
True```

```>>> isnat(np.timedelta64('NAT').view('i8'))
False```