Test element-wise for NaT (not a time) in Numpy

NumpyServer Side ProgrammingProgramming

To test element-wise for NaT, use the numpy.isnat() method in Python Numpy. It checks the value for datetime or timedelta data type.

The condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Steps

At first, import the required library −

import numpy as np

To test element-wise for NaT, use the numpy.isnat() method in Python Numpy. It checks the value for datetime or timedelta data type −

Checking for dates. The datetime64 data type accepts the string “NAT”, in any combination of lowercase/uppercase letters, for a “Not A Time” value −

print("Check for NaT? ", np.isnat(np.datetime64("NaT")))
print("Check for NaT? ", np.isnat(np.datetime64("2021-12-22")))
print("Check for NaT? ", np.isnat(np.datetime64('2021-12', 'D')))
print("Check for NaT? ", np.isnat(np.datetime64(1, 'Y')))
print("Check for NaT? ", np.isnat(np.datetime64('2005-02-25T03:30')))
print("Check for NaT? ", np.isnat(np.datetime64('nat')))
print("Check for NaT? ", np.isnat(np.datetime64("5")))
print("Check for NaT? ", np.isnat(np.datetime64('nAt')))

Example

import numpy as np

# To test element-wise for NaT, use the numpy.nat() method in Python Numpy
# It checks the for datetime or timedelta data type.

# Checking for dates
# The datetime64 data type accepts the string “NAT”,
# in any combination of lowercase/uppercase letters, for a “Not A Time” value.
print("Check for NaT? ", np.isnat(np.datetime64("NaT")))
print("Check for NaT? ", np.isnat(np.datetime64("2021-12-22")))
print("Check for NaT? ", np.isnat(np.datetime64('2021-12', 'D')))
print("Check for NaT? ", np.isnat(np.datetime64(1, 'Y')))
print("Check for NaT? ", np.isnat(np.datetime64('2005-02-25T03:30')))
print("Check for NaT? ", np.isnat(np.datetime64('nat')))
print("Check for NaT? ", np.isnat(np.datetime64("5")))
print("Check for NaT? ", np.isnat(np.datetime64('nAt')))

Output

Check for NaT? True
Check for NaT? False
Check for NaT? False
Check for NaT? False
Check for NaT? False
Check for NaT? True
Check for NaT? False
Check for NaT? True
raja
Updated on 08-Feb-2022 05:56:33

Advertisements