Skip to content

fix(indexing): select coarse datetime64 slices beyond ns range (#10975) - #11927

Merged
headtr1ck merged 5 commits into
pydata:mainfrom
aniruddhaadak80:fix/chunksizes-isel-dim
Nov 25, 2026
Merged

headtr1ck merged 5 commits into
pydata:mainfrom
aniruddhaadak80:fix/chunksizes-isel-dim

Conversation

@aniruddhaadak80

Copy link
Copy Markdown
Contributor

Description

Closes #10975.

DataArray.sel/Dataset.sel with a string slice (e.g. slice("2400-01-01", "2420-01-01")) on a datetime64 index whose unit is coarser than nanoseconds raised OutOfBoundsDatetime, even when every bound is perfectly representable in the index's unit:

import numpy as np
import xarray as xr

months = np.arange("2389-01", "2490-01", dtype="datetime64[M]")
times = months.astype("datetime64[s]")
da = xr.DataArray(np.arange(times.size), dims="time", coords={"time": times})

da.sel(time=slice("2400-01-01", "2420-01-01"))
# pandas.errors.OutOfBoundsDatetime:
#   Cannot cast 2400-01-02 00:00:00 to unit='ns' without overflow.

This is the shape of index produced by CFDatetimeCoder(time_unit="s"), so it is a realistic path for data beyond pandas' nanosecond range.

The failure comes from _query_slice in xarray/core/indexes.py, which passes the slice bounds straight to pandas.Index.slice_indexer. For string bounds pandas parses them at nanosecond resolution and overflows for dates outside 1677–2262, regardless of the index's own resolution. Passing np.datetime64 scalars in the index's unit avoids that parsing: DatetimeIndex(["2400-01-01", ...], dtype="datetime64[s]").slice_indexer(np.datetime64("2400-01-01", "s"), np.datetime64("2420-01-01", "s")) returns the correct slice.

The fix catches OutOfBoundsDatetime, and only for a DatetimeIndex whose dtype is not datetime64[ns], re-tries with string bounds converted to the index's unit. All other cases (including nanosecond indexes) keep the current behaviour and error. No change to public API.

A doc/whats-new.rst entry was added under the unreleased "Bug Fixes" section.

Checklist

  • Closes .sel() fails on datetime64[s] object #10975
  • Tests added
  • User visible changes (including notable bug fixes) are documented in whats-new.rst
  • New functions/methods are listed in api.rst (no new functions or methods)

Tests

Regression test in xarray/tests/test_indexes.py parametrized over datetime64[s], [ms] and [us], building a monthly index spanning 2390–2409 and selecting a slice in 2400–2402.

Actual results in a worktree-local environment (Python 3.12, NumPy 2.5.3, pandas 3.0.6, Windows). A local sitecustomize.py was used on PYTHONPATH to give the tagless editable dask checkout a parseable __version__; nothing from it is in the diff.

$ python -m pytest -o addopts="" xarray/tests/test_indexes.py -k coarse_unit_outside -q
  with fix:             3 passed
  with core/indexes.py reverted: 3 failed, 85 deselected
    (pandas.errors.OutOfBoundsDatetime: Cannot cast 2400-01-02 00:00:00 to unit='ns')

$ python -m pytest -o addopts="" xarray/tests/test_indexes.py -q
88 passed

$ python -m pytest -o addopts="" xarray/tests/test_indexes.py \
    xarray/tests/test_dataarray.py xarray/tests/test_dataset.py \
    -q -k "sel or index or datetime"
9 failed, 371 passed, 1 skipped, 1000 deselected, 3 xfailed

The 9 failures are pre-existing environment failures, unrelated to this change: pandas 3.0.6 refuses to import its optional xarray integration because this tagless editable install reports xarray 0.0.0 (ImportError: Pandas requires version '2024.10.0' or newer of 'xarray'). They are all categorical/from_dataframe/extension-array tests and fail the same way without the fix.

Lint/format:

$ python -m ruff check xarray/core/indexes.py xarray/tests/test_indexes.py
All checks passed!
$ python -m ruff format --check xarray/core/indexes.py xarray/tests/test_indexes.py
2 files already formatted

Limitations

  • Verified on Python 3.12 / NumPy 2.5.3 / pandas 3.0.6 / Windows only.
  • The fallback converts string bounds to the index's unit only after pandas raises OutOfBoundsDatetime. This deliberately does not change semantics for in-range strings, where pandas' partial-string period handling (e.g. "2400" meaning the whole year) is preserved. For out-of-range partial strings the fallback uses the start of the parsed period, which is the only representation pandas cannot provide itself.
  • cftime indexes and PeriodIndex are unaffected.
  • The full test suite and docs build were not run on this host.

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.
      Tools: OpenCode (AI coding agent)

An AI coding agent located the failure in _query_slice, drafted the fallback and the regression test, and ran the verification above. I reviewed the diff and each claimed result.

Copilot AI balanced review requested due to automatic review settings November 22, 2026 16:18

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@headtr1ck headtr1ck left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks @aniruddhaadak80! I pushed a small fix and merged main.

np.datetime64(stop, unit) only gives the first instant of a partial string, but pandas includes the whole period, e.g. slice("2400-03", "2400-03") selected only 2400-03-01T00:00:00 instead of all of March. The stop bound is now parsed at the string's own precision and moved to the end of its period, like pandas' DatetimeIndex._parsed_string_to_bounds does. Since the Gregorian calendar repeats every 400 years, I checked that selections in 2400 now match the same selections in 2000.

[This is Claude Code on behalf of Michael Niklas]

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@headtr1ck headtr1ck added the plan to merge Final call for comments label Nov 23, 2026
@headtr1ck
headtr1ck enabled auto-merge (squash) November 25, 2026 21:35
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@headtr1ck
headtr1ck merged commit 3848a69 into pydata:main Nov 25, 2026
51 checks passed
zenedgexlabs pushed a commit to zenedgexlabs/xarray that referenced this pull request Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

plan to merge Final call for comments topic-indexing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.sel() fails on datetime64[s] object

3 participants