`to_xarray` for time coords beyond `np.datetime64[ns]`
Assessment
This issue has not been assessed yet.
Description
Field.to_xarray() can fail or else will raise a warning when a field contains a valid CF time coordinate with dates beyond the range supported by numpy.datetime64[ns]. This isn't unrealistic in practice: the values would only have to exceed ~2262 and climate science data could easily cover the 23rd century and beyond. Indeed this was noticed with our extra_data.pp test file which has a time coordinate of: time(100) = [2290-06-01 00:00:00, ..., 2389-06-01 00:00:00] 360_day.
As noticed first in a failure for a cf-python (not cfdm, I am yet to update those Actions workflows) CI job for the test test_xarray.xarrayTest.test_FieldList_to_xarray_from_disk and also seen once locally (but since then I haven't been able to recreate it further locally, possibly some subtle environment change 🤔 ). But I do always see a warning if not an error, so we should address this. See below for both cases.
Solution
I need to determine whether this is an issue of a cfdm/ours or of cftime (or otherwise, but those are by far the likely candidates given the below traceback etc.) before proposing a solution. Nothing jumps out from the cftime Issue Tracker but I've not had a good chance to look properly.
Related warnings and errors
It is unclear yet under which circumstances this leads to the error, which I can only reliably produce via the CI jobs, else when it isn't terminal and gives the warning, but likely this is due to a deprecation somewhere at a certain version cutoff:
The warning
As shown interactively:
>>> cfdm.read("extra_data.pp")
[<Field: air_temperature(ncdim%dimension1(1), height(1), time(100), long_name=site(3)) K>]
>>> f = cfdm.read("extra_data.pp")
>>> f = f[0]
>>> ds = f.to_xarray()
/home/slb93/git-repos/cfdm/cfdm/read_write/netcdf/xarray_dataset.py:314: SerializationWarning: Unable to decode time axis into full numpy.datetime64[ns] objects, continuing using cftime.datetime objects instead, reason: dates out of range. To silence this warning use a coarser resolution 'time_unit' or specify 'use_cftime=True'.
var = xr.decode_cf(
/home/slb93/miniconda3/envs/cf-env-312-numpy2/lib/python3.12/site-packages/dask/_task_spec.py:764: SerializationWarning: Unable to decode time axis into full numpy.datetime64[ns] objects, continuing using cftime.datetime objects instead, reason: dates out of range. To silence this warning use a coarser resolution 'time_unit' or specify 'use_cftime=True'.
return self.func(*new_argspec)
The error
As shown from the output of a CI job, namely test-on-linux (3.13). Interestingly, before the other jobs on Ubuntu auto-cancelled triggered by this Python 3.13 job failing, the 3.14 job fully passed, so clearly it didn't error on that:
======================================================================
ERROR: test_FieldList_to_xarray_from_disk (test_xarray.xarrayTest.test_FieldList_to_xarray_from_disk)
Test FieldList.to_xarray from datasets read from disk.
----------------------------------------------------------------------
Traceback (most recent call last):
File "pandas/_libs/tslibs/timedeltas.pyx", line 2014, in pandas._libs.tslibs.timedeltas._Timedelta._as_creso
File "pandas/_libs/tslibs/np_datetime.pyx", line 698, in pandas._libs.tslibs.np_datetime.convert_reso
OverflowError: result would overflow
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/coding/times.py", line 563, in decode_cf_datetime
dates = _decode_datetime_with_pandas(
flat_num_dates, units, calendar, time_unit
)
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/coding/times.py", line 512, in _decode_datetime_with_pandas
_check_date_for_units_since_refdate(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
flat_num_dates.max(), time_unit, ref_date
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/coding/times.py", line 422, in _check_date_for_units_since_refdate
return (ref_date + delta).as_unit(ref_date.unit)
~~~~~~~~~^~~~~~~
File "pandas/_libs/tslibs/timestamps.pyx", line 561, in pandas._libs.tslibs.timestamps._Timestamp.__add__
File "pandas/_libs/tslibs/timedeltas.pyx", line 2017, in pandas._libs.tslibs.timedeltas._Timedelta._as_creso
pandas.errors.OutOfBoundsTimedelta: Cannot cast 1072693248 days 00:00:00 to unit='ns' without overflow.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/coding/times.py", line 355, in _decode_cf_datetime_dtype
result = decode_cf_datetime(
example_value, units, calendar, use_cftime, time_unit
)
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/coding/times.py", line 567, in decode_cf_datetime
dates = _decode_datetime_with_cftime(
flat_num_dates.astype(float), units, calendar
)
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/coding/times.py", line 383, in _decode_datetime_with_cftime
cftime.num2date(num_dates, units, calendar, only_use_cftime_datetimes=True)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "src/cftime/_cftime.pyx", line 625, in cftime._cftime.num2date
File "src/cftime/_cftime.pyx", line 419, in cftime._cftime.cast_to_int
OverflowError: time values outside range of 64 bit signed integers
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/work/cf-python/cf-python/main/cf/test/test_xarray.py", line 105, in test_FieldList_to_xarray_from_disk
ds = f.to_xarray()
File "/home/runner/work/cf-python/cf-python/main/cf/mixin/fielddomainlist.py", line 365, in to_xarray
return write(self, fmt="XARRAY", group=group)
File "/home/runner/work/cf-python/cf-python/cfdm/cfdm/read_write/write.py", line 1085, in __new__
return netcdf.write(
~~~~~~~~~~~~^
fields,
^^^^^^^
...<31 lines>...
hdf5_expansion_factor=hdf5_expansion_factor,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/home/runner/work/cf-python/cf-python/cfdm/cfdm/decorators.py", line 171, in verbose_override_wrapper
return method_with_verbose_kwarg(*args, **kwargs)
File "/home/runner/work/cf-python/cf-python/cfdm/cfdm/read_write/netcdf/netcdfwrite.py", line 6305, in write
return self.write_vars["dataset"].to_xarray()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "/home/runner/work/cf-python/cf-python/cfdm/cfdm/read_write/netcdf/xarray_dataset.py", line 199, in to_xarray
ds.coords[name] = var.to_xarray()
~~~~~~~~~~~~~^^
File "/home/runner/work/cf-python/cf-python/cfdm/cfdm/read_write/netcdf/xarray_dataset.py", line 314, in to_xarray
var = xr.decode_cf(
~~~~~~~~~~~~^
var.to_dataset(name=self.name),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...<4 lines>...
drop_variables=None,
^^^^^^^^^^^^^^^^^^^^
)[self.name]
^
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/conventions.py", line 585, in decode_cf
vars, attrs, coord_names = decode_cf_variables(
~~~~~~~~~~~~~~~~~~~^
vars,
^^^^^
...<7 lines>...
decode_timedelta=decode_timedelta,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/conventions.py", line 410, in decode_cf_variables
new_vars[k] = decode_cf_variable(
~~~~~~~~~~~~~~~~~~^
k,
^^
...<8 lines>...
decode_timedelta=_item_or_default(decode_timedelta, k, None),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/conventions.py", line 237, in decode_cf_variable
var = decode_times.decode(var, name=name)
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/coding/times.py", line 1414, in decode
dtype = _decode_cf_datetime_dtype(
data, units, calendar, self.use_cftime, self.time_unit
)
File "/home/runner/miniconda3/envs/cf-latest/lib/python3.13/site-packages/xarray/coding/times.py", line 367, in _decode_cf_datetime_dtype
raise ValueError(msg) from err
ValueError: unable to decode time units 'days since 1970-01-01 00:00:00' with 'the default calendar'. Try opening your dataset with decode_times=False or installing cftime if it is not installed.
Raised while decoding variable 'time' with value <xarray.Variable (station: 3, timeseries: 26)> Size: 624B
dask.array<cfdm_harden_mask, shape=(3, 26), dtype=float64, chunksize=(1, 26), chunktype=numpy.ndarray>
Attributes:
long_name: time
standard_name: time
units: days since 1970-01-01 00:00:00
bounds: time_bounds
- Dominant language
- Python
- Stars
- 32
- Forks
- 14
- Avg merge
- 3d 20h
- Merged PRs (30d)
- 1
Getting set up
- No Dockerfile or Docker Compose file
- No pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from NCAS-CMS/cfdm
-
Convert to/from iris cubesPossibly taken @davidhassell claimed this 4 days ago. Openenhancement
Difficulty 5/5 Over a week Newbie friendliness 20/100
-
Convert from/to `xarray`Possibly taken @davidhassell claimed this 6 days ago. Opendataset read dataset write enhancement xarray
Difficulty 4/5 3-5 days Newbie friendliness 20/100
-
enhancement
Difficulty 3/5 1-2 days Newbie friendliness 57/100
-
documentation
Difficulty 4/5 3-5 days Newbie friendliness 48/100
-
Conformance: UGRID check failure reporting missing attrMay be free again @sadielbartholomew claimed this 66 days ago, and no pull request is open. Openbug UGRID
Similar issues
-
eegprep-lean: set channel types from the Zarr group's channel_typePossibly taken @claude claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 70/100
sccn/eegprep#668 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
blacklanternsecurity/bbot#3679 ·
Maintainers usually reply within 2 days
-
Link Checker ReportOpenBot Type: Bug Type: Documentation
Difficulty 1/5 Under an hour Newbie friendliness 85/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 80/100
speakeasy-api/speakeasy#2159 ·
Maintainers usually reply within 1 day