NumPy or Pandas: How to check a Value or an Array for NaT

Borislav Hadzhiev

Last updated: Apr 12, 2024

Reading timeยท4 min

- NumPy: How to check a Value or an Array for NaT
- Checking a Value or an Array for NaT with
`pandas.isnull()`

- Checking a value for NaT by converting it to a string

**You can use the numpy.isnat() method to check a value or an array for
NaT.**

**The isnat() method returns True if the value is NaT and False
otherwise.**

main.py

`import numpy as np not_a_time = np.datetime64('NaT') print(not_a_time) # ๐๏ธ NaT print('-' * 50) if np.isnat(not_a_time): # ๐๏ธ This runs print('The value has a type of NaT') else: print('The value does NOT have a type of NaT') print('-' * 50) dt = np.datetime64('2024-09-24') print(np.isnat(dt)) # ๐๏ธ False`

The code for this article is available on GitHub

The code sample uses the `numpy.isnat()`

method to check if a single value is
`NaT`

(not a time).

The method will return `True`

if the value is `NaT`

and `False`

otherwise.

The same approach can be used to check if each value in an array is `NaT`

.

main.py

`import numpy as np arr = np.array(['NaT', 2, 4, 'NaT', 6], dtype='datetime64[D]') # ๐๏ธ [ True False False True False] print(np.isnat(arr))`

We directly passed the array to the `numpy.nat()`

method.

The method returns `True`

if the element is `NaT`

and `False`

otherwise.

Note that the `numpy.isnat()`

method fails when checking for Pandas `NaT`

.

main.py

`import numpy as np import pandas as pd # โ๏ธ TypeError: ufunc 'isnat' is only defined for datetime and timedelta. print(np.isnat(pd.NaT))`

If you need to be able to check for both `pandas`

and NumPy `NaT`

, use the
`pandas.isnull()`

method from the next subheading.

`pandas.isnull()`

You can also use the
pandas.isnull
method to check a value or an array for `NaT`

.

Make sure you have the pandas module installed to be able to run the code sample.

shell

`pip install numpy pandas # or with pip3 pip3 install numpy pandas`

Now import the module and use the `pandas.isnull()`

method.

main.py

`import numpy as np import pandas as pd not_a_time = np.datetime64('nat') print(not_a_time) # ๐๏ธ NaT print('-' * 50) if pd.isnull(not_a_time): # ๐๏ธ this runs print('The value has a type of NaT') else: print('The value does NOT have a type of NaT')`

The code for this article is available on GitHub

The `pandas.isnull()`

method takes a scalar or an array-like object and
indicates whether the values are missing:

`NaN`

in numeric arrays.`None`

or`NaN`

in object arrays.`NaT`

(not a time) in`datetime`

objects.

You can also use the method to check an array for `NaT`

values.

main.py

`import numpy as np import pandas as pd arr = np.array(['NaT', 2, 4, 'NaT', 6], dtype='datetime64[D]') # ๐๏ธ [ True False False True False] print(pd.isnull(arr))`

A `True`

value is returned for each array element that is `NaT`

, otherwise,
`False`

is returned.

The `pandas.isnull()`

method properly checks for both NumPy and Pandas `NaT`

values, so it should be your preferred approach.

main.py

`import numpy as np import pandas as pd print(pd.isnull(pd.NaT)) # ๐๏ธ True print(pd.isnull(np.datetime64('nat'))) # ๐๏ธ True`

You might also see the pandas.isna() method being used.

main.py

`import numpy as np import pandas as pd print(pd.isna(pd.NaT)) # ๐๏ธ True print(pd.isna(np.datetime64('nat'))) # ๐๏ธ True`

The `pandas.isna()`

method is just an alias for `pandas.isnull()`

.

You can also check a value for NaT by converting it to a string.

main.py

`import numpy as np not_a_time = np.datetime64('nat') print(not_a_time) # ๐๏ธ NaT print('-' * 50) if str(not_a_time) == 'NaT': # ๐๏ธ this runs print('The value has a type of NaT') else: print('The value does NOT have a type of NaT')`

The code for this article is available on GitHub

Converting a `datetime`

object with a type of `NaT`

to a string returns the
string `"NaT"`

.

main.py

`import numpy as np not_a_time = np.datetime64('nat') print(not_a_time) # ๐๏ธ NaT print(repr(str(not_a_time))) # ๐๏ธ 'NaT'`

Therefore, we can compare the resulting string to `"NaT"`

.

main.py

`import numpy as np not_a_time = np.datetime64('nat') print(not_a_time) # ๐๏ธ NaT print(str(not_a_time) == 'NaT') # ๐๏ธ True dt = np.datetime64('2024-09-24') print(str(dt) == 'NaT') # ๐๏ธ False`

The expression returns `True`

if the value has a type of `NaT`

and `False`

otherwise.

However, note that this approach can only be used to check if a single value is
`NaT`

.

If you need to check if each value in an array is `NaT`

, use the approach from
the previous subheading.

You can learn more about the related topics by checking out the following tutorials:

- OverflowError: Python int too large to convert to C long
- TypeError: Field elements must be 2- or 3-tuples, got 1
- ValueError: Expected 2D array, got 1D array instead [Fixed]
- TypeError: ufunc 'isnan' not supported for the input types
- Convert a Row to a Column Header in a Pandas DataFrame
- Arrays used as indices must be of integer (or boolean) type
- Get the column names of a NumPy ndarray in Python
- ValueError: No axis named X for object type DataFrame
- Calculate the average (mean) of 2 NumPy arrays
- Interpolating NaN values in a NumPy Array in Python
- Reading specific columns from an Excel File in Pandas
- NumPy: Calculate the distance between a Point and a Line
- Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of X
- Get N random Rows from a NumPy Array in Python
- Create Date column from Year, Month and Day in Pandas
- Remove the Duplicate elements from a NumPy Array
- NumPy: Apply a Mask from one Array to another Array
- How to iterate over the Columns of a NumPy Array
- Pandas: Find an element's Index in Series [7 Ways]
- All the input arrays must have same number of dimensions
- Only integer scalar arrays can be converted to a scalar index
- ValueError: Index contains duplicate entries, cannot reshape
- TypeError: type numpy.ndarray doesn't define __round__ method