Skip to content

Time series utilities

Python representations of multidimensional time series and interop with Python cffi

ConvertibleToTimestamp = Union[str, datetime, np.datetime64, pd.Timestamp] module-attribute

types that can be converted with relative unambiguity to a pandas Timestamp

TimeSeriesLike = Union[pd.Series, pd.DataFrame, xr.DataArray] module-attribute

types that can represent time series

XR_UNITS_ATTRIB_ID = 'units' module-attribute

key for the units attribute on xarray DataArray objects

as_datetime64(t)

Convert, if possible, to a numpy datetime64

Parameters:

Name Type Description Default
t ConvertibleToTimestamp

date time value to convert

required

Raises:

Type Description
ValueError

input value is not supported, notably values with time zone informations are excluded

TypeError

unexpected input type

Returns:

Type Description
datetime64

np.datetime64: value as a datetime64

Source code in cinterop/timeseries.py
def as_datetime64(t: ConvertibleToTimestamp) -> np.datetime64:
    """Convert, if possible, to a numpy datetime64

    Args:
        t (ConvertibleToTimestamp): date time value to convert

    Raises:
        ValueError: input value is not supported, notably values with time zone informations are excluded
        TypeError: unexpected input type

    Returns:
        np.datetime64: value as a datetime64
    """
    return as_timestamp(t).to_datetime64()

as_pydatetime(t)

Convert, if possible, to a datetime

Parameters:

Name Type Description Default
t ConvertibleToTimestamp

date time value to convert

required

Raises:

Type Description
ValueError

input value is not supported, notably values with time zone informations are excluded

TypeError

unexpected input type

Returns:

Name Type Description
datetime datetime

value as a datetime

Source code in cinterop/timeseries.py
def as_pydatetime(t: ConvertibleToTimestamp) -> datetime:
    """Convert, if possible, to a datetime

    Args:
        t (ConvertibleToTimestamp): date time value to convert

    Raises:
        ValueError: input value is not supported, notably values with time zone informations are excluded
        TypeError: unexpected input type

    Returns:
        datetime: value as a datetime
    """
    return as_timestamp(t).to_pydatetime()

as_timestamp(t)

Converts, if possible, a value to a pandas Timestamp

Parameters:

Name Type Description Default
t ConvertibleToTimestamp

date time value to convert

required

Raises:

Type Description
ValueError

input value is not supported, notably values with time zone informations are excluded

TypeError

unexpected input type

Returns:

Type Description
Timestamp

pd.Timestamp: date time as a pandas Timestamp

Source code in cinterop/timeseries.py
def as_timestamp(t: ConvertibleToTimestamp) -> pd.Timestamp:
    """Converts, if possible, a value to a pandas `Timestamp`

    Args:
        t (ConvertibleToTimestamp): date time value to convert

    Raises:
        ValueError: input value is not supported, notably values with time zone informations are excluded
        TypeError: unexpected input type

    Returns:
        pd.Timestamp: date time as a pandas Timestamp
    """
    # initially work around a breaking change in pandas 1.x: "Expected unicode, got numpy.str_'

    # In the future we may support time zones. This is a typically fraught thing, so by default let's stay away from it
    if _is_convertible_to_timestamp(t):
        if isinstance(t, pd.Timestamp):
            if t.tz is not None:
                raise ValueError(
                    "Not supported - Cannot pass a datetime or Timestamp with tzinfo with the tz parameter. Use tz_convert instead"
                )
            else:
                return t
        elif isinstance(t, datetime):
            if t.tzinfo is not None:
                raise ValueError(
                    "Not supported - Cannot pass a datetime or Timestamp with tzinfo with the tz parameter. Use tz_convert instead"
                )
        parsed = pd.Timestamp(t)
        if parsed.tz is not None:
            raise ValueError(
                "To avoid ambiguities time zones are not supported. All date times must be 'naive'"
            )
        else:
            return parsed
    else:
        raise TypeError(
            "Cannot convert to a timestamp the object of type" + str(type(t))
        )

create_daily_time_index(start, n)

Creates a daily time index

Parameters:

Name Type Description Default
start ConvertibleToTimestamp

first datetime in the time index

required
n int

length of the index

required

Returns:

Type Description
DatetimeIndex

pd.DatetimeIndex: a time index suitable for a time series.

Source code in cinterop/timeseries.py
def create_daily_time_index(start: ConvertibleToTimestamp, n: int) -> pd.DatetimeIndex:
    """Creates a daily time index

    Args:
        start (ConvertibleToTimestamp): first datetime in the time index
        n (int): length of the index

    Returns:
        pd.DatetimeIndex: a time index suitable for a time series.
    """
    start = as_datetime64(start)
    return pd.date_range(
        start, periods=n, freq="D"
    )  # much faster than list comprehension, see https://jmp75.github.io/work-blog/c++/python/performance/runtime/2022/08/09/python-profiling-interop.html

create_ensemble_forecasts_series(npx, ens_index, lead_time_index, time_index)

Create an ensemble forecasts time series (i.e. a series of ensembles of series)

Source code in cinterop/timeseries.py
def create_ensemble_forecasts_series(
    npx: np.ndarray,
    ens_index: List,
    lead_time_index: List,
    time_index: Union[List, pd.DatetimeIndex],
) -> xr.DataArray:
    """Create an ensemble forecasts time series (i.e. a series of ensembles of series)"""
    if npx is None:
        npx = np.empty(
            shape=(len(ens_index), len(lead_time_index), len(time_index)), dtype=float
        )
        npx[:] = np.nan
    return xr.DataArray(
        npx,
        coords=[ens_index, lead_time_index, time_index],
        dims=[ENSEMBLE_DIMNAME, LEADTIME_DIMNAME, TIME_DIMNAME],
    )

create_ensemble_series(npx, ens_index, time_index)

Create an ensemble (i.e. special type of multi-variate) time series

Source code in cinterop/timeseries.py
def create_ensemble_series(
    npx: np.ndarray, ens_index: List, time_index: Union[List, pd.DatetimeIndex]
) -> xr.DataArray:
    """Create an ensemble (i.e. special type of multi-variate) time series"""
    return xr.DataArray(
        npx, coords=[ens_index, time_index], dims=[ENSEMBLE_DIMNAME, TIME_DIMNAME]
    )

create_even_time_index(start, time_step_seconds, n)

Creates a regular, evenly spaces time index

Parameters:

Name Type Description Default
start ConvertibleToTimestamp

first datetime in the time index

required
time_step_seconds int

time step length in seconds

required
n int

length of the index

required

Returns:

Type Description
DatetimeIndex

pd.DatetimeIndex: a time index suitable for a time series.

Source code in cinterop/timeseries.py
def create_even_time_index(
    start: ConvertibleToTimestamp, time_step_seconds: int, n: int
) -> pd.DatetimeIndex:
    """Creates a regular, evenly spaces time index

    Args:
        start (ConvertibleToTimestamp): first datetime in the time index
        time_step_seconds (int): time step length in seconds
        n (int): length of the index

    Returns:
        pd.DatetimeIndex: a time index suitable for a time series.
    """
    if time_step_seconds == 3600:
        return create_hourly_time_index(start, n)
    elif time_step_seconds == 86400:
        return create_daily_time_index(start, n)
    else:
        start = as_datetime64(start)
        delta_t = np.timedelta64(time_step_seconds, "s")
        # Note: below appears to be a few times faster than pd.date_range with a freq=Dateoffset for some reasons.
        return pd.DatetimeIndex([start + delta_t * i for i in range(n)])

create_hourly_time_index(start, n)

Creates an hourly time index

Parameters:

Name Type Description Default
start ConvertibleToTimestamp

first datetime in the time index

required
n int

length of the index

required

Returns:

Type Description
DatetimeIndex

pd.DatetimeIndex: a time index suitable for a time series.

Source code in cinterop/timeseries.py
def create_hourly_time_index(start: ConvertibleToTimestamp, n: int) -> pd.DatetimeIndex:
    """Creates an hourly time index

    Args:
        start (ConvertibleToTimestamp): first datetime in the time index
        n (int): length of the index

    Returns:
        pd.DatetimeIndex: a time index suitable for a time series.
    """
    start = as_datetime64(start)
    return pd.date_range(
        start, periods=n, freq="h"
    )  # much faster than list comprehension

create_monthly_time_index(start, n)

Creates a monthly time index

Parameters:

Name Type Description Default
start ConvertibleToTimestamp

first datetime in the time index

required
n int

length of the index

required

Raises:

Type Description
ValueError

day of month of the start date is more than 28

Returns:

Type Description
DatetimeIndex

pd.DatetimeIndex: a time index suitable for a time series.

Source code in cinterop/timeseries.py
def create_monthly_time_index(
    start: ConvertibleToTimestamp, n: int
) -> pd.DatetimeIndex:
    """Creates a monthly time index

    Args:
        start (ConvertibleToTimestamp): first datetime in the time index
        n (int): length of the index

    Raises:
        ValueError: day of month of the start date is more than 28

    Returns:
        pd.DatetimeIndex: a time index suitable for a time series.
    """
    pdstart = as_timestamp(start)
    if pdstart.day > 28:
        raise ValueError(
            "Monthly time indices require a day of month less than 29. End of months indices are not yet supported."
        )
    start = as_datetime64(start)
    return pd.date_range(start, periods=n, freq=pd.tseries.offsets.DateOffset(months=1))

create_single_series(npx, time_index)

Create an uni-variate time series

Source code in cinterop/timeseries.py
def create_single_series(
    npx: np.ndarray, time_index: Union[List, pd.DatetimeIndex]
) -> xr.DataArray:
    """Create an uni-variate time series"""
    npx = npx.squeeze()
    assert len(npx.shape) == 1
    return xr.DataArray(npx, coords=[time_index], dims=[TIME_DIMNAME])

end_ts(x)

Gets the ending date of a time series

Parameters:

Name Type Description Default
x TimeSeriesLike

time series

required

Returns:

Name Type Description
Any datetime64

end of the series

Source code in cinterop/timeseries.py
def end_ts(x: TimeSeriesLike) -> np.datetime64:
    """Gets the ending date of a time series

    Args:
        x (TimeSeriesLike): time series

    Returns:
        Any: end of the series
    """
    return __ts_index(x)[-1]

mk_daily_xarray_series(data, start_date, dim_name=None, units=None, colnames=None, fill_miss_func=None)

Create a daily xarray time series

Parameters:

Name Type Description Default
data Union[ndarray, TimeSeriesLike]

data from which to create the xarray series

required
start_date ConvertibleToTimestamp

start date of the daily time series

required
dim_name str

the name of the dimension for a multivariate series. Ignored if univariate. Defaults to None.

None
units str

units in the time series. Defaults to None.

None
colnames Optional[List[str]]

names of the columns in a multivariate series. Defaults to None.

None
fill_miss_func Optional[Callable[[TsArrayLike], TsArrayLike]]

optional function that fills in missing values (np.nan). Defaults to None.

None

Raises:

Type Description
NotImplementedError

Input arguments are not consistent.

Returns:

Type Description
DataArray

xr.DataArray: output xarray time series with at least a dimension "time"

Source code in cinterop/timeseries.py
def mk_daily_xarray_series(
    data: Union[np.ndarray, TimeSeriesLike],
    start_date: ConvertibleToTimestamp,
    dim_name: str = None,
    units: str = None,
    colnames: Optional[List[str]] = None,
    fill_miss_func: Optional[Callable[[TsArrayLike], TsArrayLike]] = None,
) -> xr.DataArray:
    """Create a daily xarray time series

    Args:
        data (Union[np.ndarray, TimeSeriesLike]): data from which to create the xarray series
        start_date (ConvertibleToTimestamp): start date of the daily time series
        dim_name (str, optional): the name of the dimension for a multivariate series. Ignored if univariate. Defaults to None.
        units (str, optional): units in the time series. Defaults to None.
        colnames (Optional[List[str]], optional): names of the columns in a multivariate series. Defaults to None.
        fill_miss_func (Optional[Callable[[TsArrayLike], TsArrayLike]], optional): optional function that fills in missing values (np.nan). Defaults to None.

    Raises:
        NotImplementedError: Input arguments are not consistent.

    Returns:
        xr.DataArray: output xarray time series with at least a dimension "time"
    """
    _check_series_data(data, dim_name)
    n = data.shape[0]
    time_index = create_daily_time_index(start_date, n)
    return mk_xarray_series(data, dim_name, units, time_index, colnames, fill_miss_func)

mk_even_step_xarray_series(data, start_date, time_step_seconds, dim_name=None, units=None, colnames=None, fill_miss_func=None)

Create an xarray time series with an even time step

Parameters:

Name Type Description Default
data Union[ndarray, TimeSeriesLike]

data from which to create the xarray series

required
start_date ConvertibleToTimestamp

start date of the daily time series

required
time_step_seconds int

time step length in seconds

required
dim_name str

the name of the dimension for a multivariate series. Ignored if univariate. Defaults to None.

None
units str

units in the time series. Defaults to None.

None
colnames Optional[List[str]]

names of the columns in a multivariate series. Defaults to None.

None
fill_miss_func Optional[Callable[[TsArrayLike], TsArrayLike]]

optional function that fills in missing values (np.nan). Defaults to None.

None

Raises:

Type Description
NotImplementedError

Input arguments are not consistent.

Returns:

Type Description
DataArray

xr.DataArray: output xarray time series with at least a dimension "time"

Source code in cinterop/timeseries.py
def mk_even_step_xarray_series(
    data: Union[np.ndarray, TimeSeriesLike],
    start_date: ConvertibleToTimestamp,
    time_step_seconds: int,
    dim_name: str = None,
    units: str = None,
    colnames: Optional[List[str]] = None,
    fill_miss_func: Optional[Callable[[TsArrayLike], TsArrayLike]] = None,
) -> xr.DataArray:
    """Create an xarray time series with an even time step

    Args:
        data (Union[np.ndarray, TimeSeriesLike]): data from which to create the xarray series
        start_date (ConvertibleToTimestamp): start date of the daily time series
        time_step_seconds (int): time step length in seconds
        dim_name (str, optional): the name of the dimension for a multivariate series. Ignored if univariate. Defaults to None.
        units (str, optional): units in the time series. Defaults to None.
        colnames (Optional[List[str]], optional): names of the columns in a multivariate series. Defaults to None.
        fill_miss_func (Optional[Callable[[TsArrayLike], TsArrayLike]], optional): optional function that fills in missing values (np.nan). Defaults to None.

    Raises:
        NotImplementedError: Input arguments are not consistent.

    Returns:
        xr.DataArray: output xarray time series with at least a dimension "time"
    """
    _check_series_data(data, dim_name)
    n = data.shape[0]
    time_index = create_even_time_index(start_date, time_step_seconds, n)
    return mk_xarray_series(data, dim_name, units, time_index, colnames, fill_miss_func)

mk_hourly_xarray_series(data, start_date, dim_name=None, units=None, colnames=None, fill_miss_func=None)

Create an hourly xarray time series

Parameters:

Name Type Description Default
data Union[ndarray, TimeSeriesLike]

Data from which to create the xarray series

required
dim_name str

the name of the dimension for a multivariate series. Ignored if univariate. Defaults to None.

None
units str

units in the time series. Defaults to None.

None
time_index Optional[Union[List, DatetimeIndex]]

the time index of the series. Optional if the input data already has a time index, such as a pandas series. Defaults to None.

required
colnames Optional[List[str]]

names of the columns in a multivariate series. Defaults to None.

None
fill_miss_func Optional[Callable[[TsArrayLike], TsArrayLike]]

optional function that fills in missing values (np.nan). Defaults to None.

None

Raises:

Type Description
NotImplementedError

Input arguments are not consistent.

Returns:

Type Description
DataArray

xr.DataArray: output xarray time series with at least a dimension "time"

Source code in cinterop/timeseries.py
def mk_hourly_xarray_series(
    data: Union[np.ndarray, TimeSeriesLike],
    start_date: ConvertibleToTimestamp,
    dim_name: str = None,
    units: str = None,
    colnames: Optional[List[str]] = None,
    fill_miss_func: Optional[Callable[[TsArrayLike], TsArrayLike]] = None,
) -> xr.DataArray:
    """Create an hourly xarray time series

    Args:
        data (Union[np.ndarray, TimeSeriesLike]): Data from which to create the xarray series
        dim_name (str, optional): the name of the dimension for a multivariate series. Ignored if univariate. Defaults to None.
        units (str, optional): units in the time series. Defaults to None.
        time_index (Optional[Union[List, pd.DatetimeIndex]], optional): the time index of the series. Optional if the input data already has a time index, such as a pandas series. Defaults to None.
        colnames (Optional[List[str]], optional): names of the columns in a multivariate series. Defaults to None.
        fill_miss_func (Optional[Callable[[TsArrayLike], TsArrayLike]], optional): optional function that fills in missing values (np.nan). Defaults to None.

    Raises:
        NotImplementedError: Input arguments are not consistent.

    Returns:
        xr.DataArray: output xarray time series with at least a dimension "time"
    """
    _check_series_data(data, dim_name)
    n = data.shape[0]
    time_index = create_hourly_time_index(start_date, n)
    return mk_xarray_series(data, dim_name, units, time_index, colnames, fill_miss_func)

mk_xarray_series(data, dim_name=None, units=None, time_index=None, colnames=None, fill_miss_func=None)

Create an xarray time series

Parameters:

Name Type Description Default
data Union[ndarray, TimeSeriesLike]

data from which to create the xarray series

required
dim_name str

the name of the dimension for a multivariate series. Ignored if univariate. Defaults to None.

None
units str

units in the time series. Defaults to None.

None
time_index Optional[Union[List, DatetimeIndex]]

the time index of the series. Optional if the input data already has a time index, such as a pandas series. Defaults to None.

None
colnames Optional[List[str]]

names of the columns in a multivariate series. Defaults to None.

None
fill_miss_func Optional[Callable[[TsArrayLike], TsArrayLike]]

optional function that fills in missing values (np.nan). Defaults to None.

None

Raises:

Type Description
NotImplementedError

Input arguments are not consistent.

Returns:

Type Description
DataArray

xr.DataArray: output xarray time series with at least a dimension "time"

Source code in cinterop/timeseries.py
def mk_xarray_series(
    data: Union[np.ndarray, TimeSeriesLike],
    dim_name: str = None,
    units: str = None,
    time_index: Optional[Union[List, pd.DatetimeIndex]] = None,
    colnames: Optional[List[str]] = None,
    fill_miss_func: Optional[Callable[[TsArrayLike], TsArrayLike]] = None,
) -> xr.DataArray:
    """Create an xarray time series

    Args:
        data (Union[np.ndarray, TimeSeriesLike]): data from which to create the xarray series
        dim_name (str, optional): the name of the dimension for a multivariate series. Ignored if univariate. Defaults to None.
        units (str, optional): units in the time series. Defaults to None.
        time_index (Optional[Union[List, pd.DatetimeIndex]], optional): the time index of the series. Optional if the input data already has a time index, such as a pandas series. Defaults to None.
        colnames (Optional[List[str]], optional): names of the columns in a multivariate series. Defaults to None.
        fill_miss_func (Optional[Callable[[TsArrayLike], TsArrayLike]], optional): optional function that fills in missing values (np.nan). Defaults to None.

    Raises:
        NotImplementedError: Input arguments are not consistent.

    Returns:
        xr.DataArray: output xarray time series with at least a dimension "time"
    """
    if len(data.shape) > 2:
        raise NotImplementedError("data must be at most of dimension 2")
    if len(data.shape) > 1 and dim_name is None:
        raise NotImplementedError(
            "data has more than one dimension, so the name of the second dimension 'dim_name' must be provided"
        )
    if time_index is None:
        if not isinstance(data, pd.Series):
            raise NotImplementedError(
                "if time_index is None data must be a pandas Series"
            )
        else:
            time_index = data.index
    if colnames is None and len(data.shape) > 1:
        if not isinstance(data, pd.Series):
            raise NotImplementedError(
                "if colnames is None and data of shape 2, data must be a pandas Series"
            )
        else:
            colnames = data.columns
    if fill_miss_func is not None:
        data = fill_miss_func(data)
    if len(data.shape) > 1:
        x = xr.DataArray(
            data, coords=[time_index, colnames], dims=[TIME_DIM_NAME, dim_name]
        )
    else:
        x = xr.DataArray(data, coords=[time_index], dims=[TIME_DIM_NAME])
    if units is not None:
        set_xr_units(x, units)
    return x

pd_series_to_xr_series(series)

Converts a pandas series to an xarray

Source code in cinterop/timeseries.py
def pd_series_to_xr_series(series: pd.Series) -> xr.DataArray:
    """Converts a pandas series to an xarray"""
    assert isinstance(series, pd.Series)
    return create_single_series(series.values, series.index)

set_xr_units(x, units)

Sets the units attribute of an xr.DataArray. No effect if x is not a dataarray

Parameters:

Name Type Description Default
x DataArray

data array

required
units str

units descriptor

required
Source code in cinterop/timeseries.py
def set_xr_units(x: xr.DataArray, units: str) -> None:
    """Sets the units attribute of an xr.DataArray. No effect if x is not a dataarray

    Args:
        x (xr.DataArray): data array
        units (str): units descriptor
    """
    if units is None:
        return
    if isinstance(x, xr.DataArray):
        x.attrs[XR_UNITS_ATTRIB_ID] = units

slice_pd_time_series(data, from_date=None, to_date=None)

Subset a time series to a period

Parameters:

Name Type Description Default
data Series

input xarray time series

required
from_date ConvertibleToTimestamp

date, convertible to a timestamp. Defaults to None.

None
to_date ConvertibleToTimestamp

end date of the slice. Inclusive. Defaults to None.

None

Returns:

Type Description
Series

pd.Series: a subset time series

Examples:

slice_pd_time_series(unaccounted_indus, from_date='1980-04-01', to_date='2000-04-01')

Source code in cinterop/timeseries.py
def slice_pd_time_series(
    data: pd.Series,
    from_date: ConvertibleToTimestamp = None,
    to_date: ConvertibleToTimestamp = None,
) -> pd.Series:
    """Subset a time series to a period

    Args:
        data (pd.Series): input xarray time series
        from_date (ConvertibleToTimestamp, optional): date, convertible to a timestamp. Defaults to None.
        to_date (ConvertibleToTimestamp, optional): end date of the slice. Inclusive. Defaults to None.

    Returns:
        pd.Series: a subset time series

    Examples:
        slice_pd_time_series(unaccounted_indus, from_date='1980-04-01', to_date='2000-04-01')
    """
    dt = data.index
    tt = _time_interval_indx(dt, from_date, to_date)
    return data[tt]

slice_xr_time_series(data, from_date=None, to_date=None)

Subset a time series to a period

Parameters:

Name Type Description Default
data DataArray

input xarray time series

required
from_date ConvertibleToTimestamp

date, convertible to a timestamp. Defaults to None.

None
to_date ConvertibleToTimestamp

end date of the slice. Inclusive. Defaults to None.

None

Returns:

Type Description
DataArray

xr.DataArray: a subset time series

Examples:

slice_xr_time_series(unaccounted_indus, from_date='1980-04-01', to_date='2000-04-01')

Source code in cinterop/timeseries.py
def slice_xr_time_series(
    data: xr.DataArray,
    from_date: ConvertibleToTimestamp = None,
    to_date: ConvertibleToTimestamp = None,
) -> xr.DataArray:
    """Subset a time series to a period

    Args:
        data (xr.DataArray): input xarray time series
        from_date (ConvertibleToTimestamp, optional): date, convertible to a timestamp. Defaults to None.
        to_date (ConvertibleToTimestamp, optional): end date of the slice. Inclusive. Defaults to None.

    Returns:
        xr.DataArray: a subset time series

    Examples:
        slice_xr_time_series(unaccounted_indus, from_date='1980-04-01', to_date='2000-04-01')
    """
    dt = data.time.values
    tt = _time_interval_indx(dt, from_date, to_date)
    return data.sel(time=tt)

start_ts(x)

Gets the starting date of a time series

Parameters:

Name Type Description Default
x TimeSeriesLike

time series

required

Returns:

Name Type Description
Any datetime64

start of the series

Source code in cinterop/timeseries.py
def start_ts(x: TimeSeriesLike) -> np.datetime64:
    """Gets the starting date of a time series

    Args:
        x (TimeSeriesLike): time series

    Returns:
        Any: start of the series
    """
    return __ts_index(x)[0]

ts_window(ts, from_date=None, to_date=None)

Gets a temporal window of a time series

Parameters:

Name Type Description Default
ts TimeSeriesLike

pandas dataframe, series, or xarray DataArray

required
from_date ConvertibleToTimestamp

start date of the window. Defaults to None.

None
to_date ConvertibleToTimestamp

end date of the window. Defaults to None.

None

Raises:

Type Description
TypeError

unhandled input time for ts

Returns:

Name Type Description
TimeSeriesLike TimeSeriesLike

Subset window of the full time series

Examples:

ts_window(unaccounted_indus, from_date='1980-04-01', to_date='2000-04-01')

Source code in cinterop/timeseries.py
def ts_window(
    ts: TimeSeriesLike,
    from_date: ConvertibleToTimestamp = None,
    to_date: ConvertibleToTimestamp = None,
) -> "TimeSeriesLike":
    """Gets a temporal window of a time series

    Args:
        ts (TimeSeriesLike): pandas dataframe, series, or xarray DataArray
        from_date (ConvertibleToTimestamp, optional): start date of the window. Defaults to None.
        to_date (ConvertibleToTimestamp, optional): end date of the window. Defaults to None.

    Raises:
        TypeError: unhandled input time for `ts`

    Returns:
        TimeSeriesLike: Subset window of the full time series

    Examples:
        ts_window(unaccounted_indus, from_date='1980-04-01', to_date='2000-04-01')
    """
    if isinstance(ts, xr.DataArray):
        return slice_xr_time_series(ts, from_date, to_date)
    elif isinstance(ts, pd.Series) or isinstance(ts, pd.DataFrame):
        return slice_pd_time_series(ts, from_date, to_date)
    else:
        raise TypeError("Not supported: " + str(type(ts)))

xr_ts_end(x)

Source code in cinterop/timeseries.py
def xr_ts_end(x: TimeSeriesLike) -> np.datetime64:
    """Deprecated: use end_ts"""
    return end_ts(x)

xr_ts_start(x)

Source code in cinterop/timeseries.py
def xr_ts_start(x: TimeSeriesLike) -> np.datetime64:
    """Deprecated: use start_ts"""
    return start_ts(x)