Repository navigation
Conversation
…oogleapis#19190) Signed-off-by: Roxen-AS <akash.arjun12@gmail.com>
There was a problem hiding this comment.
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.
| __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["): |
There was a problem hiding this comment.
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:There was a problem hiding this comment.
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>
|
Hi maintainers, gentle check-in on this PR — all test checks pass and the branch is clean; it is just awaiting codeowner approval ( |
| ) # Integers are stored with nanosecond precision. | ||
| return x.astype(_NP_BOX_DTYPE).item().time() | ||
|
|
||
| __return_deltas = {"timedelta", "timedelta64", "timedelta64[ns]", "<m8", _NP_DTYPE} |
There was a problem hiding this comment.
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(): |
There was a problem hiding this comment.
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": |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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?
TimeArrayuses1970-01-01only as an internal backing date (__init__.py:93). Exposing it makes a storage detail public API. Keeping only"<m8[ns]"still fixes db-dtypes: TimeArray.astype("datetime64[ns]") returns a timedelta64[ns] array #19190 by raisingTypeError.lstrip("<>=|")makesastype(">m8[ns]")silently return<m8[ns](wrong endianness) and accepts invalid strings like"<<<m8[ns]".
Signed-off-by: Roxen-AS <akash.arjun12@gmail.com>
|
Thank you for the review @sindhuvy! Addressed all four suggestions in
Verified locally: |
Fixes #19190
Summary
_NP_DTYPE("datetime64[ns]") with"<m8[ns]"inTimeArray.__return_deltasinpackages/db-dtypes/db_dtypes/__init__.pysoTimeArray.astype("datetime64[ns]")falls through tosuper().astype(...)(raisingTypeError) rather than returningtimedelta64[ns]._NP_DTYPEconstant.test_timearray_astype_datetime64inpackages/db-dtypes/tests/unit/test_dtypes.py.