diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 815e13733f7a2..d8f7ca4448d47 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -561,6 +561,7 @@ Other API changes - The ``.str``-accessor has been disabled for 1-level :class:`MultiIndex`, use :meth:`MultiIndex.to_flat_index` if necessary (:issue:`23679`) - Removed support of gtk package for clipboards (:issue:`26563`) - Using an unsupported version of Beautiful Soup 4 will now raise an ``ImportError`` instead of a ``ValueError`` (:issue:`27063`) +- :meth:`Series.to_excel` and :meth:`DataFrame.to_excel` will now raise a ``ValueError`` when saving timezone aware data. (:issue:`27008`, :issue:`7056`) .. _whatsnew_0250.deprecations: diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 5792f6e2a5a08..66a00bf9ab054 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -402,6 +402,10 @@ def _format_value(self, val): val = '-{inf}'.format(inf=self.inf_rep) elif self.float_format is not None: val = float(self.float_format % val) + if getattr(val, 'tzinfo', None) is not None: + raise ValueError('Excel does not support datetimes with ' + 'timezones. Please ensure that datetimes ' + 'are timezone unaware before writing to Excel.') return val def _format_header_mi(self): diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index a4fdcdf70a3ea..8f20136f1ea4b 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -1178,6 +1178,21 @@ def test_merged_cell_custom_objects(self, engine, merge_cells, ext): expected.index = expected.index.astype(np.float64) tm.assert_frame_equal(expected, result) + @pytest.mark.parametrize('dtype', [None, object]) + def test_raise_when_saving_timezones(self, engine, ext, dtype, + tz_aware_fixture): + # GH 27008, GH 7056 + tz = tz_aware_fixture + data = pd.Timestamp('2019', tz=tz) + df = DataFrame([data], dtype=dtype) + with pytest.raises(ValueError, match="Excel does not support"): + df.to_excel(self.path) + + data = data.to_pydatetime() + df = DataFrame([data], dtype=dtype) + with pytest.raises(ValueError, match="Excel does not support"): + df.to_excel(self.path) + class TestExcelWriterEngineTests: