diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index be4a1b12cc39..10007e82d167 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -7418,6 +7418,15 @@ def hist(self, x, bins=None, range=None, density=False, weights=None, x = cbook._reshape_2D(x, 'x') nx = len(x) # number of datasets + for arr in x: + if len(arr) > 0 and isinstance( + arr[0], (datetime.timedelta, np.timedelta64) + ): + raise TypeError( + "Axes.hist does not currently support timedelta inputs. " + "Convert to numeric values (e.g., .total_seconds()) first." + ) + # Process unit information. _process_unit_info sets the unit and # converts the first dataset; then we convert each following dataset # one at a time. diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index a58b6f88e5ea..52bc2e3e277f 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2461,6 +2461,21 @@ def test_hist_log_barstacked(): assert axs[0].get_ylim() == axs[1].get_ylim() +def test_hist_timedelta_raises(): + import numpy as np + import matplotlib.pyplot as plt + + fig, ax = plt.subplots() + + arr_np = np.array([1, 2, 5, 7], dtype="timedelta64[D]") + with pytest.raises(TypeError, match="does not currently support timedelta inputs"): + ax.hist(arr_np) + + arr_py = [datetime.timedelta(seconds=i) for i in range(5)] + with pytest.raises(TypeError, match="does not currently support timedelta inputs"): + ax.hist(arr_py) + + @image_comparison(['hist_bar_empty.png'], remove_text=True) def test_hist_bar_empty(): # From #3886: creating hist from empty dataset raises ValueError