How to create a 'NaT' in Python?

Viewed 1642

I need to create a "NaT" (the analog of float('NaN') but with time) in Python. Can this be done natively in Python or using the datetime library? How?

I know that numpy and pandas can do this (or something similar), but I feel that if I need to import a library for this it should be datetime, not numpy or pandas.

1 Answers

Unfortunately, it does not look like datetime supports this notation. Looking at the code for how NaT is implemented in pandas, it looks like they create a class of type datetime, and insert the desired NaT behavior by overriding the operations. This leads me to believe it does not exist in datetime or they would use that. See pandas _NaT class

Also this is further evidenced by this output testing conversion of pandas timestamps to datetimes.

import pandas as pd

pd.Timestamp('10/2020').to_pydatetime()
Out[2]: datetime.datetime(2020, 10, 1, 0, 0)

pd.Timestamp('NaT').to_pydatetime()
Out[3]: NaT

type(pd.Timestamp('NaT').to_pydatetime())
Out[4]: pandas._libs.tslibs.nattype.NaTType

Note that the NaT does not produce a datetime.datetime type.

In conclusion your options are:

  1. Implement your own NaT class of type datetime similar to pandas (may be difficult).

  2. Use numpy. In numpy the NaT can be found with np.datetime64('nat'). Numpy documentation about working with missing time. here

  3. Use pandas. In pandas the NaT can be found with pd.NaT or interpreted through timestamp pd.Timestamp('nat'). The Pandas documentation there is a full section about working with missing data and how it is handled with Datetimes here

Related