The isnat() function of numpy module

Overview:

  • The NumPy function isnat() takes a NumPy array-like as parameter whose elements are of type np.datetime64 and np.timedelta64 and checks each element whether it is an invalid timestamp. If the timestamp is invalid the result is True. If the timestamp is valid the result is False. The results are returned as an ndarray containing Boolean values.

  • When the input to the function is a scalar numpy.isnat() returns a single Boolean value.

  • When the timestamps passed are not of type np.datetime64 or np.timedelta64, numpy.isnat() raises a TypeError stating "TypeError: ufunc 'isnat' is only defined for np.datetime64 and np.timedelta64."

Example 1:

# Example Python program that validates
# timestamp elements of a numpy ndarray
import numpy

# Create an ndarray of timestamps.
# Resolution is upto minutes
timestamps = numpy.ndarray(shape = (2, 2), 
                           dtype = 'datetime64[m]')

# Seconds part will be discarded
timestamps[0][0] = numpy.datetime64("2024-10-22T06:31:01")

# Minutes part will be assigned 00
timestamps[0][1] = "2024-10-22T06"

# Hours part and minutes part will be assigned 00
timestamps[1][0] = "2024-10-22"

# An NaT entry is created
timestamps[1][1] = "NaT"
print("An ndarray of timestamps:")
print(timestamps)

# Check the ndarray has NaTs  
tsResults = numpy.isnat(timestamps)
print("Results array for NaT check:")
print(tsResults)

Output:

An ndarray of timestamps:

[['2024-10-22T06:31' '2024-10-22T06:00']

 ['2024-10-22T00:00'              'NaT']]

Results array for NaT check:

[[False False]

 [False  True]]

Example 2:

# Example Python program that uses numpy.isnat()
# to check whether the timestamp returned by datetime.time()
# is invalid 
import numpy
import datetime

ts1 = datetime.time()

# Is ts1 invalid?
result = numpy.isnat(ts1)
print(result)

Output:

Traceback (most recent call last):

  File "/Users/vinodh/PythonProgs/time_stamp_check.py", line 10, in <module>

    result = numpy.isnat(ts1)

             ^^^^^^^^^^^^^^^^

TypeError: ufunc 'isnat' is only defined for np.datetime64 and np.timedelta64.

 


Copyright 2024 © pythontic.com