MCPcopy
hub / github.com/pydata/xarray / decode_cf_timedelta

Function decode_cf_timedelta

xarray/coding/times.py:678–717  ·  view source on GitHub ↗

Given an array of numeric timedeltas in netCDF format, convert it into a numpy timedelta64 ["s", "ms", "us", "ns"] array.

(
    num_timedeltas, units: str, time_unit: PDDatetimeUnitOptions = "ns"
)

Source from the content-addressed store, hash-verified

676
677
678def decode_cf_timedelta(
679 num_timedeltas, units: str, time_unit: PDDatetimeUnitOptions = "ns"
680) -> np.ndarray:
681 """Given an array of numeric timedeltas in netCDF format, convert it into a
682 numpy timedelta64 ["s", "ms", "us", "ns"] array.
683 """
684 num_timedeltas = to_numpy(num_timedeltas)
685 unit = _netcdf_to_numpy_timeunit(units)
686
687 # special case empty arrays
688 is_empty_array = num_timedeltas.size == 0
689
690 with warnings.catch_warnings():
691 warnings.filterwarnings("ignore", "All-NaN slice encountered", RuntimeWarning)
692 if not is_empty_array:
693 _check_timedelta_range(np.nanmin(num_timedeltas), unit, time_unit)
694 _check_timedelta_range(np.nanmax(num_timedeltas), unit, time_unit)
695
696 timedeltas = _numbers_to_timedelta(
697 num_timedeltas, unit, "s", "timedeltas", target_unit=time_unit
698 )
699 pd_timedeltas = pd.to_timedelta(ravel(timedeltas))
700
701 if not is_empty_array and np.isnat(timedeltas).all():
702 empirical_unit = time_unit
703 else:
704 empirical_unit = pd_timedeltas.unit
705
706 if is_empty_array or np.timedelta64(1, time_unit) > np.timedelta64(
707 1, empirical_unit
708 ):
709 time_unit = empirical_unit
710
711 if time_unit not in {"s", "ms", "us", "ns"}:
712 raise ValueError(
713 f"time_unit must be one of 's', 'ms', 'us', or 'ns'. Got: {time_unit}"
714 )
715
716 result = pd_timedeltas.as_unit(time_unit).to_numpy()
717 return reshape(result, num_timedeltas.shape)
718
719
720def _unit_timedelta_cftime(units: str) -> timedelta:

Calls 8

to_numpyFunction · 0.90
ravelFunction · 0.90
reshapeFunction · 0.90
_check_timedelta_rangeFunction · 0.85
_numbers_to_timedeltaFunction · 0.85
allMethod · 0.45
to_numpyMethod · 0.45

Used in the wild real call sites across dependent graphs

searching dependent graphs…