|
9 | 9 | import numpy as np
|
10 | 10 | import pandas as pd
|
11 | 11 |
|
| 12 | +from xarray.coding import times |
12 | 13 | from xarray.core import dtypes, duck_array_ops, indexing
|
13 | 14 | from xarray.core.pycompat import is_duck_dask_array
|
14 | 15 | from xarray.core.variable import Variable
|
@@ -239,6 +240,16 @@ def encode(self, variable: Variable, name: T_Name = None):
|
239 | 240 | # Ensure _FillValue is cast to same dtype as data's
|
240 | 241 | encoding["_FillValue"] = dtype.type(fv)
|
241 | 242 | fill_value = pop_to(encoding, attrs, "_FillValue", name=name)
|
| 243 | + # retrieve _FillValue in case of np.datetime64 |
| 244 | + # see GH 7817 |
| 245 | + if np.issubdtype(data.dtype, np.datetime64): |
| 246 | + units = encoding.get("units", None) |
| 247 | + if isinstance(units, str) and "since" in units: |
| 248 | + delta, _ = times._unpack_netcdf_time_units(units) |
| 249 | + delta = times._netcdf_to_numpy_timeunit(delta) |
| 250 | + fill_value = np.datetime64(fill_value.item(), delta).astype( |
| 251 | + "datetime64[ns]" |
| 252 | + ) |
242 | 253 | if not pd.isnull(fill_value):
|
243 | 254 | data = duck_array_ops.fillna(data, fill_value)
|
244 | 255 |
|
@@ -275,7 +286,17 @@ def decode(self, variable: Variable, name: T_Name = None):
|
275 | 286 | )
|
276 | 287 |
|
277 | 288 | dtype, decoded_fill_value = dtypes.maybe_promote(data.dtype)
|
278 |
| - |
| 289 | + # retrieve _FillValue in case of np.datetime64 |
| 290 | + # see GH 7817 |
| 291 | + if np.issubdtype(data.dtype, np.datetime64) and decoded_fill_value.astype( |
| 292 | + np.int64 |
| 293 | + ) == np.datetime64("NaT").astype(np.int64): |
| 294 | + delta, _ = times._unpack_netcdf_time_units(encoding["units"]) |
| 295 | + delta = times._netcdf_to_numpy_timeunit(delta) |
| 296 | + encoded_fill_values = { |
| 297 | + np.datetime64(encfill.item(), delta).astype("datetime64[ns]") |
| 298 | + for encfill in encoded_fill_values |
| 299 | + } |
279 | 300 | if encoded_fill_values:
|
280 | 301 | transform = partial(
|
281 | 302 | _apply_mask,
|
|
0 commit comments