Skip to content

fix(db-dtypes): replace _NP_DTYPE with <m8[ns] in TimeArray.__return_deltas (#19190) - #19255

Open
Roxen-AS wants to merge 3 commits into
googleapis:mainfrom
Roxen-AS:fix/db-dtypes-timearray-astype-datetime
Open

Roxen-AS wants to merge 3 commits into
googleapis:mainfrom
Roxen-AS:fix/db-dtypes-timearray-astype-datetime

Conversation

@Roxen-AS

@Roxen-AS Roxen-AS commented Nov 28, 2026 •

Copy link
Copy Markdown

Fixes #19190

Summary

  • Replaced _NP_DTYPE ("datetime64[ns]") with "<m8[ns]" in TimeArray.__return_deltas in packages/db-dtypes/db_dtypes/__init__.py so TimeArray.astype("datetime64[ns]") falls through to super().astype(...) (raising TypeError) rather than returning timedelta64[ns].
  • Removed the now-unused _NP_DTYPE constant.
  • Added test_timearray_astype_datetime64 in packages/db-dtypes/tests/unit/test_dtypes.py.

@Roxen-AS
Roxen-AS requested review from a team as code owners November 28, 2026 16:06
@Roxen-AS
Roxen-AS requested review from sindhuvy and removed request for a team November 28, 2026 16:06

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request updates the astype method in db-dtypes to support casting to datetime types (such as datetime, datetime64, and <M8) directly from the underlying ndarray, and adds corresponding unit tests, including a test for casting dbtime to datetime64[ns]. The reviewer suggests making the dtype string parsing more robust by supporting standard NumPy dtype representations that do not use the little-endian prefix (<), such as big-endian (>), native (=), or no prefix at all.

Comment on lines +171 to 187
__return_deltas = {"timedelta", "timedelta64", "timedelta64[ns]", "<m8", "<m8[ns]"}

def astype(self, dtype, copy=True):
deltas = self._ndarray - _NPEPOCH
stype = str(dtype)
if stype.startswith("datetime"):
if stype == "datetime" or stype == "datetime64":
dtype = self._ndarray.dtype
return self._ndarray.astype(dtype, copy=copy)
elif stype.startswith("<M8"):
if stype == "<M8":
dtype = self._ndarray.dtype
return self._ndarray.astype(dtype, copy=copy)

deltas = self._ndarray - _NPEPOCH
if stype in self.__return_deltas:
return deltas
elif stype.startswith("timedelta64[") or stype.startswith("<m8["):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation only checks for <M8 and <m8 prefixes, which assumes a specific endianness (little-endian) and format. However, standard NumPy dtype strings can also be specified without endianness prefixes (e.g., M8[ns], m8[ns]) or with other endianness prefixes (e.g., >M8[ns], =M8[ns]).

To make the casting more robust and prevent potential TypeErrors when users pass these standard formats, we should update the checks to look for "M8" and "m8" anywhere in the string representation, and expand __return_deltas to include other common variations.

    __return_deltas = {
        "timedelta",
        "timedelta64",
        "timedelta64[ns]",
        "m8",
        "m8[ns]",
        "<m8",
        "<m8[ns]",
        ">m8",
        ">m8[ns]",
        "=m8",
        "=m8[ns]",
    }

    def astype(self, dtype, copy=True):
        stype = str(dtype)
        if stype.startswith("datetime"):
            if stype == "datetime" or stype == "datetime64":
                dtype = self._ndarray.dtype
            return self._ndarray.astype(dtype, copy=copy)
        elif "M8" in stype:
            if stype in ("M8", "<M8", ">M8", "=M8"):
                dtype = self._ndarray.dtype
            return self._ndarray.astype(dtype, copy=copy)

        deltas = self._ndarray - _NPEPOCH
        if stype in self.__return_deltas:
            return deltas
        elif stype.startswith("timedelta64[") or "m8[" in stype:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in commit 19fa00e04dc: updated TimeArray.astype and DateArray.astype to strip NumPy endianness prefixes (<, >, =, |) before checking for M8 / m8 / m8[, and expanded unit tests in test_dtypes.py to cover =M8[ns], M8[ns], M8, =M8[us], M8[us], and =M8.

…datetime conversion

Signed-off-by: Roxen-AS <akash.arjun12@gmail.com>
@sindhuvy sindhuvy added kokoro:force-run Add this label to force Kokoro to re-run the tests. and removed kokoro:force-run Add this label to force Kokoro to re-run the tests. labels Dec 2, 2026
@Roxen-AS

Roxen-AS commented Dec 2, 2026

Copy link
Copy Markdown
Author

Hi maintainers, gentle check-in on this PR — all test checks pass and the branch is clean; it is just awaiting codeowner approval (multi-approvers). Please let me know if anything else is needed. Thank you!

) # Integers are stored with nanosecond precision.
return x.astype(_NP_BOX_DTYPE).item().time()

__return_deltas = {"timedelta", "timedelta64", "timedelta64[ns]", "<m8", _NP_DTYPE}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this was the last use of _NP_DTYPE, so could we remove that constant too?

assert pd.isna(b[2]) and str(b[2]) == "NaT"


def test_time_array_astype_datetime_issue_19190():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: ideally we name the test based on what it does rather than the issue number, maybe test_timearray_astype_datetime64?

if stype == "<M8":
clean_stype = stype.lstrip("<>=|")
if stype.startswith("datetime") or clean_stype.startswith("M8"):
if stype in ("datetime", "datetime64") or clean_stype == "M8":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we revert this DateArray.astype change too?

clean_stype.startswith("M8") now catches timezone-aware strings like DateArray.astype("M8[ns, UTC]") and passes them to NumPy, which breaks a cast that works on main (raises TypeError: Invalid datetime unit in metadata string "[ns, UTC]").

return deltas
elif stype.startswith("timedelta64[") or stype.startswith("<m8["):
elif stype.startswith("timedelta64[") or clean_stype.startswith("m8["):
return deltas.astype(dtype, copy=False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this! Could we narrow this to just the "<m8[ns]" fix in __return_deltas and drop the datetime branch and clean_stype here?

Signed-off-by: Roxen-AS <akash.arjun12@gmail.com>
@Roxen-AS Roxen-AS changed the title fix(db-dtypes): cast TimeArray to datetime64 instead of timedelta64 (#19190) fix(db-dtypes): replace _NP_DTYPE with <m8[ns] in TimeArray.__return_deltas (#19190) Dec 3, 2026
@Roxen-AS

Roxen-AS commented Dec 3, 2026

Copy link
Copy Markdown
Author

Thank you for the review @sindhuvy! Addressed all four suggestions in 43efbc5090a:

  1. Narrowed TimeArray to replacing _NP_DTYPE with "<m8[ns]" in __return_deltas and dropped the datetime / clean_stype changes so the internal 1970-01-01 backing date stays private and astype("datetime64[ns]") raises TypeError.
  2. Removed the now-unused _NP_DTYPE constant.
  3. Reverted the DateArray.astype changes so timezone-aware casts like M8[ns, UTC] keep their existing behavior.
  4. Reverted test_asdatetime and renamed the new unit test to test_timearray_astype_datetime64.

Verified locally: pytest tests/unit (321 passed), ruff check, and ruff format --check all pass.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

db-dtypes: TimeArray.astype("datetime64[ns]") returns a timedelta64[ns] array

2 participants