| 1522 | return variable |
| 1523 | |
| 1524 | def decode(self, variable: Variable, name: T_Name = None) -> Variable: |
| 1525 | units = variable.attrs.get("units", None) |
| 1526 | has_timedelta_units = isinstance(units, str) and units in TIME_UNITS |
| 1527 | has_timedelta_dtype = has_timedelta64_encoding_dtype(variable.attrs) |
| 1528 | is_dtype_decodable = has_timedelta_units and has_timedelta_dtype |
| 1529 | is_units_decodable = has_timedelta_units |
| 1530 | if (is_dtype_decodable and self.decode_via_dtype) or ( |
| 1531 | is_units_decodable and self.decode_via_units |
| 1532 | ): |
| 1533 | dims, data, attrs, encoding = unpack_for_decoding(variable) |
| 1534 | units = pop_to(attrs, encoding, "units") |
| 1535 | if is_dtype_decodable: |
| 1536 | attrs_dtype = attrs.pop("dtype") |
| 1537 | if self.time_unit is None: |
| 1538 | time_unit = resolve_time_unit_from_attrs_dtype(attrs_dtype, name) |
| 1539 | else: |
| 1540 | time_unit = self.time_unit |
| 1541 | else: |
| 1542 | if self.time_unit is None: |
| 1543 | time_unit = "ns" |
| 1544 | else: |
| 1545 | time_unit = self.time_unit |
| 1546 | |
| 1547 | # Handle edge case that decode_via_dtype=False and |
| 1548 | # decode_via_units=True, and timedeltas were encoded with a |
| 1549 | # dtype attribute. We need to remove the dtype attribute |
| 1550 | # to prevent an error during round tripping. |
| 1551 | if has_timedelta_dtype: |
| 1552 | attrs.pop("dtype") |
| 1553 | |
| 1554 | dtype = np.dtype(f"timedelta64[{time_unit}]") |
| 1555 | transform = partial(decode_cf_timedelta, units=units, time_unit=time_unit) |
| 1556 | data = lazy_elemwise_func(data, transform, dtype=dtype) |
| 1557 | return Variable(dims, data, attrs, encoding, fastpath=True) |
| 1558 | else: |
| 1559 | return variable |