We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[BUG] PolynomialTrendForecaster does not work with period index of frequency 30T
**Describe the bug**
PolynomialTrendForecaster does not work with period index of frequency 30T (30 mnins) due to incorrect X values 


**To Reproduce**

```python
import numpy as np
import pandas as pd
from sktime.forecasting.trend import PolynomialTrendForecaster


np.random.seed(5005)
index = pd.date_range(
    start="2020-10-01 00:00:00", end="2020-10-01 23:30:00", freq="30T"
)
data = pd.DataFrame(
    {
        "index": index,
        "target": np.random.randint(0, 255, index.shape[0], dtype=int),
    }
).set_index("index")
data.index = data.index.to_period()

forecaster = PolynomialTrendForecaster(degree=1)
forecaster.fit(data)
```

```python-traceback
 File "c:\Users\Nikhil\OneDrive\my_libraries\my_python_libraries\pycaret\pycaret_dev\time_series_debug.py", line 41, in <module>
    forecaster.fit(data)
  File "C:\Users\Nikhil\.conda\envs\pycaret_dev_sktime_0p11_3\lib\site-packages\sktime\forecasting\base\_base.py", line 265, in fit
    self._fit(y=y_inner, X=X_inner, fh=fh)
  File "C:\Users\Nikhil\.conda\envs\pycaret_dev_sktime_0p11_3\lib\site-packages\sktime\forecasting\trend.py", line 181, in _fit
    self.regressor_.fit(X, y)
  File "C:\Users\Nikhil\.conda\envs\pycaret_dev_sktime_0p11_3\lib\site-packages\sklearn\pipeline.py", line 382, in fit
    self._final_estimator.fit(Xt, y, **fit_params_last_step)
  File "C:\Users\Nikhil\.conda\envs\pycaret_dev_sktime_0p11_3\lib\site-packages\sklearn\linear_model\_base.py", line 684, in fit
    X, y = self._validate_data(
  File "C:\Users\Nikhil\.conda\envs\pycaret_dev_sktime_0p11_3\lib\site-packages\sklearn\base.py", line 596, in _validate_data
    X, y = check_X_y(X, y, **check_params)
  File "C:\Users\Nikhil\.conda\envs\pycaret_dev_sktime_0p11_3\lib\site-packages\sklearn\utils\validation.py", line 1092, in check_X_y
    check_consistent_length(X, y)
  File "C:\Users\Nikhil\.conda\envs\pycaret_dev_sktime_0p11_3\lib\site-packages\sklearn\utils\validation.py", line 387, in check_consistent_length
    raise ValueError(
ValueError: Found input variables with inconsistent numbers of samples: [1411, 48]
```

**Expected behavior**
Expected to fit correctly as it should have probably been fixed (previously reported https://github.com/alan-turing-institute/sktime/issues/1876)

**Additional context**
Originally reported here: https://github.com/pycaret/pycaret/issues/2607

**Versions**
<details>

System:
    python: 3.8.13 (default, Mar 28 2022, 06:59:08) [MSC v.1916 64 bit (AMD64)]
executable: C:\Users\Nikhil\.conda\envs\pycaret_dev_sktime_0p11_3\python.exe
   machine: Windows-10-10.0.19044-SP0

Python dependencies:
          pip: 21.2.2
   setuptools: 61.2.0
      sklearn: 1.1.1
       sktime: 0.11.4
  statsmodels: 0.13.2
        numpy: 1.21.6
        scipy: 1.8.1
       pandas: 1.4.2
   matplotlib: 3.5.2
       joblib: 1.1.0
        numba: 0.55.2
     pmdarima: 1.8.5
      tsfresh: None

</details>

<!-- Thanks for contributing! -->


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `sktime/utils/datetime.py`
Content:
```
1 #!/usr/bin/env python3 -u
2 # -*- coding: utf-8 -*-
3 """Time format related utilities."""
4 
5 __author__ = ["mloning", "xiaobenbenecho", "khrapovs"]
6 __all__ = []
7 
8 import re
9 from typing import Tuple
10 
11 import numpy as np
12 import pandas as pd
13 
14 from sktime.utils.validation.series import check_time_index, is_integer_index
15 
16 
17 def _coerce_duration_to_int(duration, freq=None):
18     """Coerce durations into integer representations for a given unit of duration.
19 
20     Parameters
21     ----------
22     duration : pd.DateOffset, pd.Timedelta, pd.TimedeltaIndex, pd.Index, int
23         Duration type or collection of duration types
24     freq : str
25         Frequency of the above duration type.
26 
27     Returns
28     -------
29     ret : int
30         Duration in integer values for given unit
31     """
32     if isinstance(duration, int):
33         return duration
34     elif isinstance(duration, pd.tseries.offsets.DateOffset):
35         return duration.n
36     elif isinstance(duration, pd.Index) and isinstance(
37         duration[0], pd.tseries.offsets.BaseOffset
38     ):
39         count = _get_intervals_count_and_unit(freq)[0]
40         return pd.Index([d.n / count for d in duration], dtype=int)
41     elif isinstance(duration, (pd.Timedelta, pd.TimedeltaIndex)):
42         count, unit = _get_intervals_count_and_unit(freq)
43         # integer conversion only works reliably with non-ambiguous units (
44         # e.g. days, seconds but not months, years)
45         try:
46             if isinstance(duration, pd.Timedelta):
47                 return int(duration / pd.Timedelta(count, unit))
48             if isinstance(duration, pd.TimedeltaIndex):
49                 return (duration / pd.Timedelta(count, unit)).astype(int)
50         except ValueError:
51             raise ValueError(
52                 "Index type not supported. Please consider using pd.PeriodIndex."
53             )
54     else:
55         raise TypeError("`duration` type not understood.")
56 
57 
58 def _get_intervals_count_and_unit(freq: str) -> Tuple[int, str]:
59     """Extract interval count and unit from frequency string.
60 
61     Supports eg: W, 3W, W-SUN, BQS, (B)Q(S)-MAR patterns, from which we
62     extract the count and the unit. See
63     https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases
64     """
65     if freq is None:
66         raise ValueError("frequency is missing")
67     m = re.match(r"(?P<count>\d*)(?P<unit>[a-zA-Z]+)$", freq)
68     if not m:
69         raise ValueError(f"pandas frequency {freq} not understood.")
70     count, unit = m.groups()
71     count = 1 if not count else int(count)
72     return count, unit
73 
74 
75 def _get_freq(x):
76     """Get unit for conversion of time deltas to integer."""
77     if hasattr(x, "freqstr"):
78         if x.freqstr is None:
79             return None
80         elif "-" in x.freqstr:
81             return x.freqstr.split("-")[0]
82         else:
83             return x.freqstr
84     else:
85         return None
86 
87 
88 def _shift(x, by=1):
89     """Shift time point `x` by a step (`by`) given frequency of `x`.
90 
91     Parameters
92     ----------
93     x : pd.Period, pd.Timestamp, int
94         Time point
95     by : int
96 
97     Returns
98     -------
99     ret : pd.Period, pd.Timestamp, int
100         Shifted time point
101     """
102     assert isinstance(x, (pd.Period, pd.Timestamp, int, np.integer)), type(x)
103     assert isinstance(by, (int, np.integer)) or is_integer_index(by), type(by)
104     if isinstance(x, pd.Timestamp):
105         if not hasattr(x, "freq") or x.freq is None:
106             raise ValueError("No `freq` information available")
107         by *= x.freq
108     return x + by
109 
110 
111 def _get_duration(x, y=None, coerce_to_int=False, unit=None):
112     """Compute duration between the time indices.
113 
114     Parameters
115     ----------
116     x : pd.Index, pd.Timestamp, pd.Period, int
117     y : pd.Timestamp, pd.Period, int, optional (default=None)
118     coerce_to_int : bool
119         If True, duration is returned as integer value for given unit
120     unit : str
121         Time unit
122 
123     Returns
124     -------
125     ret : duration type
126         Duration
127     """
128     if y is None:
129         x = check_time_index(x)
130         duration = x[-1] - x[0]
131     else:
132         assert isinstance(x, (int, np.integer, pd.Period, pd.Timestamp))
133         # check types allowing (np.integer, int) combinations to pass
134         assert type(x) is type(y) or (
135             isinstance(x, (np.integer, int)) and isinstance(x, (np.integer, int))
136         )
137         duration = x - y
138 
139     # coerce to integer result for given time unit
140     if coerce_to_int and isinstance(
141         x, (pd.PeriodIndex, pd.DatetimeIndex, pd.Period, pd.Timestamp)
142     ):
143         if unit is None:
144             # try to get the unit from the data if not given
145             unit = _get_freq(x)
146         duration = _coerce_duration_to_int(duration, freq=unit)
147     return duration
148
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/sktime/utils/datetime.py b/sktime/utils/datetime.py
--- a/sktime/utils/datetime.py
+++ b/sktime/utils/datetime.py
@@ -6,7 +6,7 @@
 __all__ = []
 
 import re
-from typing import Tuple
+from typing import Tuple, Union
 
 import numpy as np
 import pandas as pd
@@ -14,7 +14,10 @@
 from sktime.utils.validation.series import check_time_index, is_integer_index
 
 
-def _coerce_duration_to_int(duration, freq=None):
+def _coerce_duration_to_int(
+    duration: Union[int, pd.Timedelta, pd.tseries.offsets.BaseOffset, pd.Index],
+    freq: str = None,
+) -> Union[int, pd.Index]:
     """Coerce durations into integer representations for a given unit of duration.
 
     Parameters
@@ -31,8 +34,8 @@
     """
     if isinstance(duration, int):
         return duration
-    elif isinstance(duration, pd.tseries.offsets.DateOffset):
-        return duration.n
+    elif isinstance(duration, pd.tseries.offsets.BaseOffset):
+        return int(duration.n / _get_intervals_count_and_unit(freq)[0])
     elif isinstance(duration, pd.Index) and isinstance(
         duration[0], pd.tseries.offsets.BaseOffset
     ):

{"golden_diff": "diff --git a/sktime/utils/datetime.py b/sktime/utils/datetime.py\n--- a/sktime/utils/datetime.py\n+++ b/sktime/utils/datetime.py\n@@ -6,7 +6,7 @@\n __all__ = []\n \n import re\n-from typing import Tuple\n+from typing import Tuple, Union\n \n import numpy as np\n import pandas as pd\n@@ -14,7 +14,10 @@\n from sktime.utils.validation.series import check_time_index, is_integer_index\n \n \n-def _coerce_duration_to_int(duration, freq=None):\n+def _coerce_duration_to_int(\n+    duration: Union[int, pd.Timedelta, pd.tseries.offsets.BaseOffset, pd.Index],\n+    freq: str = None,\n+) -> Union[int, pd.Index]:\n     \"\"\"Coerce durations into integer representations for a given unit of duration.\n \n     Parameters\n@@ -31,8 +34,8 @@\n     \"\"\"\n     if isinstance(duration, int):\n         return duration\n-    elif isinstance(duration, pd.tseries.offsets.DateOffset):\n-        return duration.n\n+    elif isinstance(duration, pd.tseries.offsets.BaseOffset):\n+        return int(duration.n / _get_intervals_count_and_unit(freq)[0])\n     elif isinstance(duration, pd.Index) and isinstance(\n         duration[0], pd.tseries.offsets.BaseOffset\n     ):\n", "issue": "[BUG] PolynomialTrendForecaster does not work with period index of frequency 30T\n**Describe the bug**\r\nPolynomialTrendForecaster does not work with period index of frequency 30T (30 mnins) due to incorrect X values \r\n\r\n\r\n**To Reproduce**\r\n\r\n```python\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sktime.forecasting.trend import PolynomialTrendForecaster\r\n\r\n\r\nnp.random.seed(5005)\r\nindex = pd.date_range(\r\n    start=\"2020-10-01 00:00:00\", end=\"2020-10-01 23:30:00\", freq=\"30T\"\r\n)\r\ndata = pd.DataFrame(\r\n    {\r\n        \"index\": index,\r\n        \"target\": np.random.randint(0, 255, index.shape[0], dtype=int),\r\n    }\r\n).set_index(\"index\")\r\ndata.index = data.index.to_period()\r\n\r\nforecaster = PolynomialTrendForecaster(degree=1)\r\nforecaster.fit(data)\r\n```\r\n\r\n```python-traceback\r\n File \"c:\\Users\\Nikhil\\OneDrive\\my_libraries\\my_python_libraries\\pycaret\\pycaret_dev\\time_series_debug.py\", line 41, in <module>\r\n    forecaster.fit(data)\r\n  File \"C:\\Users\\Nikhil\\.conda\\envs\\pycaret_dev_sktime_0p11_3\\lib\\site-packages\\sktime\\forecasting\\base\\_base.py\", line 265, in fit\r\n    self._fit(y=y_inner, X=X_inner, fh=fh)\r\n  File \"C:\\Users\\Nikhil\\.conda\\envs\\pycaret_dev_sktime_0p11_3\\lib\\site-packages\\sktime\\forecasting\\trend.py\", line 181, in _fit\r\n    self.regressor_.fit(X, y)\r\n  File \"C:\\Users\\Nikhil\\.conda\\envs\\pycaret_dev_sktime_0p11_3\\lib\\site-packages\\sklearn\\pipeline.py\", line 382, in fit\r\n    self._final_estimator.fit(Xt, y, **fit_params_last_step)\r\n  File \"C:\\Users\\Nikhil\\.conda\\envs\\pycaret_dev_sktime_0p11_3\\lib\\site-packages\\sklearn\\linear_model\\_base.py\", line 684, in fit\r\n    X, y = self._validate_data(\r\n  File \"C:\\Users\\Nikhil\\.conda\\envs\\pycaret_dev_sktime_0p11_3\\lib\\site-packages\\sklearn\\base.py\", line 596, in _validate_data\r\n    X, y = check_X_y(X, y, **check_params)\r\n  File \"C:\\Users\\Nikhil\\.conda\\envs\\pycaret_dev_sktime_0p11_3\\lib\\site-packages\\sklearn\\utils\\validation.py\", line 1092, in check_X_y\r\n    check_consistent_length(X, y)\r\n  File \"C:\\Users\\Nikhil\\.conda\\envs\\pycaret_dev_sktime_0p11_3\\lib\\site-packages\\sklearn\\utils\\validation.py\", line 387, in check_consistent_length\r\n    raise ValueError(\r\nValueError: Found input variables with inconsistent numbers of samples: [1411, 48]\r\n```\r\n\r\n**Expected behavior**\r\nExpected to fit correctly as it should have probably been fixed (previously reported https://github.com/alan-turing-institute/sktime/issues/1876)\r\n\r\n**Additional context**\r\nOriginally reported here: https://github.com/pycaret/pycaret/issues/2607\r\n\r\n**Versions**\r\n<details>\r\n\r\nSystem:\r\n    python: 3.8.13 (default, Mar 28 2022, 06:59:08) [MSC v.1916 64 bit (AMD64)]\r\nexecutable: C:\\Users\\Nikhil\\.conda\\envs\\pycaret_dev_sktime_0p11_3\\python.exe\r\n   machine: Windows-10-10.0.19044-SP0\r\n\r\nPython dependencies:\r\n          pip: 21.2.2\r\n   setuptools: 61.2.0\r\n      sklearn: 1.1.1\r\n       sktime: 0.11.4\r\n  statsmodels: 0.13.2\r\n        numpy: 1.21.6\r\n        scipy: 1.8.1\r\n       pandas: 1.4.2\r\n   matplotlib: 3.5.2\r\n       joblib: 1.1.0\r\n        numba: 0.55.2\r\n     pmdarima: 1.8.5\r\n      tsfresh: None\r\n\r\n</details>\r\n\r\n<!-- Thanks for contributing! -->\r\n\n", "before_files": [{"content": "#!/usr/bin/env python3 -u\n# -*- coding: utf-8 -*-\n\"\"\"Time format related utilities.\"\"\"\n\n__author__ = [\"mloning\", \"xiaobenbenecho\", \"khrapovs\"]\n__all__ = []\n\nimport re\nfrom typing import Tuple\n\nimport numpy as np\nimport pandas as pd\n\nfrom sktime.utils.validation.series import check_time_index, is_integer_index\n\n\ndef _coerce_duration_to_int(duration, freq=None):\n    \"\"\"Coerce durations into integer representations for a given unit of duration.\n\n    Parameters\n    ----------\n    duration : pd.DateOffset, pd.Timedelta, pd.TimedeltaIndex, pd.Index, int\n        Duration type or collection of duration types\n    freq : str\n        Frequency of the above duration type.\n\n    Returns\n    -------\n    ret : int\n        Duration in integer values for given unit\n    \"\"\"\n    if isinstance(duration, int):\n        return duration\n    elif isinstance(duration, pd.tseries.offsets.DateOffset):\n        return duration.n\n    elif isinstance(duration, pd.Index) and isinstance(\n        duration[0], pd.tseries.offsets.BaseOffset\n    ):\n        count = _get_intervals_count_and_unit(freq)[0]\n        return pd.Index([d.n / count for d in duration], dtype=int)\n    elif isinstance(duration, (pd.Timedelta, pd.TimedeltaIndex)):\n        count, unit = _get_intervals_count_and_unit(freq)\n        # integer conversion only works reliably with non-ambiguous units (\n        # e.g. days, seconds but not months, years)\n        try:\n            if isinstance(duration, pd.Timedelta):\n                return int(duration / pd.Timedelta(count, unit))\n            if isinstance(duration, pd.TimedeltaIndex):\n                return (duration / pd.Timedelta(count, unit)).astype(int)\n        except ValueError:\n            raise ValueError(\n                \"Index type not supported. Please consider using pd.PeriodIndex.\"\n            )\n    else:\n        raise TypeError(\"`duration` type not understood.\")\n\n\ndef _get_intervals_count_and_unit(freq: str) -> Tuple[int, str]:\n    \"\"\"Extract interval count and unit from frequency string.\n\n    Supports eg: W, 3W, W-SUN, BQS, (B)Q(S)-MAR patterns, from which we\n    extract the count and the unit. See\n    https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases\n    \"\"\"\n    if freq is None:\n        raise ValueError(\"frequency is missing\")\n    m = re.match(r\"(?P<count>\\d*)(?P<unit>[a-zA-Z]+)$\", freq)\n    if not m:\n        raise ValueError(f\"pandas frequency {freq} not understood.\")\n    count, unit = m.groups()\n    count = 1 if not count else int(count)\n    return count, unit\n\n\ndef _get_freq(x):\n    \"\"\"Get unit for conversion of time deltas to integer.\"\"\"\n    if hasattr(x, \"freqstr\"):\n        if x.freqstr is None:\n            return None\n        elif \"-\" in x.freqstr:\n            return x.freqstr.split(\"-\")[0]\n        else:\n            return x.freqstr\n    else:\n        return None\n\n\ndef _shift(x, by=1):\n    \"\"\"Shift time point `x` by a step (`by`) given frequency of `x`.\n\n    Parameters\n    ----------\n    x : pd.Period, pd.Timestamp, int\n        Time point\n    by : int\n\n    Returns\n    -------\n    ret : pd.Period, pd.Timestamp, int\n        Shifted time point\n    \"\"\"\n    assert isinstance(x, (pd.Period, pd.Timestamp, int, np.integer)), type(x)\n    assert isinstance(by, (int, np.integer)) or is_integer_index(by), type(by)\n    if isinstance(x, pd.Timestamp):\n        if not hasattr(x, \"freq\") or x.freq is None:\n            raise ValueError(\"No `freq` information available\")\n        by *= x.freq\n    return x + by\n\n\ndef _get_duration(x, y=None, coerce_to_int=False, unit=None):\n    \"\"\"Compute duration between the time indices.\n\n    Parameters\n    ----------\n    x : pd.Index, pd.Timestamp, pd.Period, int\n    y : pd.Timestamp, pd.Period, int, optional (default=None)\n    coerce_to_int : bool\n        If True, duration is returned as integer value for given unit\n    unit : str\n        Time unit\n\n    Returns\n    -------\n    ret : duration type\n        Duration\n    \"\"\"\n    if y is None:\n        x = check_time_index(x)\n        duration = x[-1] - x[0]\n    else:\n        assert isinstance(x, (int, np.integer, pd.Period, pd.Timestamp))\n        # check types allowing (np.integer, int) combinations to pass\n        assert type(x) is type(y) or (\n            isinstance(x, (np.integer, int)) and isinstance(x, (np.integer, int))\n        )\n        duration = x - y\n\n    # coerce to integer result for given time unit\n    if coerce_to_int and isinstance(\n        x, (pd.PeriodIndex, pd.DatetimeIndex, pd.Period, pd.Timestamp)\n    ):\n        if unit is None:\n            # try to get the unit from the data if not given\n            unit = _get_freq(x)\n        duration = _coerce_duration_to_int(duration, freq=unit)\n    return duration\n", "path": "sktime/utils/datetime.py"}], "after_files": [{"content": "#!/usr/bin/env python3 -u\n# -*- coding: utf-8 -*-\n\"\"\"Time format related utilities.\"\"\"\n\n__author__ = [\"mloning\", \"xiaobenbenecho\", \"khrapovs\"]\n__all__ = []\n\nimport re\nfrom typing import Tuple, Union\n\nimport numpy as np\nimport pandas as pd\n\nfrom sktime.utils.validation.series import check_time_index, is_integer_index\n\n\ndef _coerce_duration_to_int(\n    duration: Union[int, pd.Timedelta, pd.tseries.offsets.BaseOffset, pd.Index],\n    freq: str = None,\n) -> Union[int, pd.Index]:\n    \"\"\"Coerce durations into integer representations for a given unit of duration.\n\n    Parameters\n    ----------\n    duration : pd.DateOffset, pd.Timedelta, pd.TimedeltaIndex, pd.Index, int\n        Duration type or collection of duration types\n    freq : str\n        Frequency of the above duration type.\n\n    Returns\n    -------\n    ret : int\n        Duration in integer values for given unit\n    \"\"\"\n    if isinstance(duration, int):\n        return duration\n    elif isinstance(duration, pd.tseries.offsets.BaseOffset):\n        return int(duration.n / _get_intervals_count_and_unit(freq)[0])\n    elif isinstance(duration, pd.Index) and isinstance(\n        duration[0], pd.tseries.offsets.BaseOffset\n    ):\n        count = _get_intervals_count_and_unit(freq)[0]\n        return pd.Index([d.n / count for d in duration], dtype=int)\n    elif isinstance(duration, (pd.Timedelta, pd.TimedeltaIndex)):\n        count, unit = _get_intervals_count_and_unit(freq)\n        # integer conversion only works reliably with non-ambiguous units (\n        # e.g. days, seconds but not months, years)\n        try:\n            if isinstance(duration, pd.Timedelta):\n                return int(duration / pd.Timedelta(count, unit))\n            if isinstance(duration, pd.TimedeltaIndex):\n                return (duration / pd.Timedelta(count, unit)).astype(int)\n        except ValueError:\n            raise ValueError(\n                \"Index type not supported. Please consider using pd.PeriodIndex.\"\n            )\n    else:\n        raise TypeError(\"`duration` type not understood.\")\n\n\ndef _get_intervals_count_and_unit(freq: str) -> Tuple[int, str]:\n    \"\"\"Extract interval count and unit from frequency string.\n\n    Supports eg: W, 3W, W-SUN, BQS, (B)Q(S)-MAR patterns, from which we\n    extract the count and the unit. See\n    https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases\n    \"\"\"\n    if freq is None:\n        raise ValueError(\"frequency is missing\")\n    m = re.match(r\"(?P<count>\\d*)(?P<unit>[a-zA-Z]+)$\", freq)\n    if not m:\n        raise ValueError(f\"pandas frequency {freq} not understood.\")\n    count, unit = m.groups()\n    count = 1 if not count else int(count)\n    return count, unit\n\n\ndef _get_freq(x):\n    \"\"\"Get unit for conversion of time deltas to integer.\"\"\"\n    if hasattr(x, \"freqstr\"):\n        if x.freqstr is None:\n            return None\n        elif \"-\" in x.freqstr:\n            return x.freqstr.split(\"-\")[0]\n        else:\n            return x.freqstr\n    else:\n        return None\n\n\ndef _shift(x, by=1):\n    \"\"\"Shift time point `x` by a step (`by`) given frequency of `x`.\n\n    Parameters\n    ----------\n    x : pd.Period, pd.Timestamp, int\n        Time point\n    by : int\n\n    Returns\n    -------\n    ret : pd.Period, pd.Timestamp, int\n        Shifted time point\n    \"\"\"\n    assert isinstance(x, (pd.Period, pd.Timestamp, int, np.integer)), type(x)\n    assert isinstance(by, (int, np.integer)) or is_integer_index(by), type(by)\n    if isinstance(x, pd.Timestamp):\n        if not hasattr(x, \"freq\") or x.freq is None:\n            raise ValueError(\"No `freq` information available\")\n        by *= x.freq\n    return x + by\n\n\ndef _get_duration(x, y=None, coerce_to_int=False, unit=None):\n    \"\"\"Compute duration between the time indices.\n\n    Parameters\n    ----------\n    x : pd.Index, pd.Timestamp, pd.Period, int\n    y : pd.Timestamp, pd.Period, int, optional (default=None)\n    coerce_to_int : bool\n        If True, duration is returned as integer value for given unit\n    unit : str\n        Time unit\n\n    Returns\n    -------\n    ret : duration type\n        Duration\n    \"\"\"\n    if y is None:\n        x = check_time_index(x)\n        duration = x[-1] - x[0]\n    else:\n        assert isinstance(x, (int, np.integer, pd.Period, pd.Timestamp))\n        # check types allowing (np.integer, int) combinations to pass\n        assert type(x) is type(y) or (\n            isinstance(x, (np.integer, int)) and isinstance(x, (np.integer, int))\n        )\n        duration = x - y\n\n    # coerce to integer result for given time unit\n    if coerce_to_int and isinstance(\n        x, (pd.PeriodIndex, pd.DatetimeIndex, pd.Period, pd.Timestamp)\n    ):\n        if unit is None:\n            # try to get the unit from the data if not given\n            unit = _get_freq(x)\n        duration = _coerce_duration_to_int(duration, freq=unit)\n    return duration\n", "path": "sktime/utils/datetime.py"}]}