Skip to content

Commit 2811464

Browse files
authored
ERR: Raise error in to_excel when saving datetimes with timezones (#27129)
* ERR: Raise error in to_excel when saving datetimes with timezones * Remove unnecessary setting of engine * Typo * Flake8
1 parent 14e1c5a commit 2811464

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

doc/source/whatsnew/v0.25.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,7 @@ Other API changes
561561
- The ``.str``-accessor has been disabled for 1-level :class:`MultiIndex`, use :meth:`MultiIndex.to_flat_index` if necessary (:issue:`23679`)
562562
- Removed support of gtk package for clipboards (:issue:`26563`)
563563
- Using an unsupported version of Beautiful Soup 4 will now raise an ``ImportError`` instead of a ``ValueError`` (:issue:`27063`)
564+
- :meth:`Series.to_excel` and :meth:`DataFrame.to_excel` will now raise a ``ValueError`` when saving timezone aware data. (:issue:`27008`, :issue:`7056`)
564565

565566
.. _whatsnew_0250.deprecations:
566567

pandas/io/formats/excel.py

+4
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,10 @@ def _format_value(self, val):
402402
val = '-{inf}'.format(inf=self.inf_rep)
403403
elif self.float_format is not None:
404404
val = float(self.float_format % val)
405+
if getattr(val, 'tzinfo', None) is not None:
406+
raise ValueError('Excel does not support datetimes with '
407+
'timezones. Please ensure that datetimes '
408+
'are timezone unaware before writing to Excel.')
405409
return val
406410

407411
def _format_header_mi(self):

pandas/tests/io/excel/test_writers.py

+15
Original file line numberDiff line numberDiff line change
@@ -1178,6 +1178,21 @@ def test_merged_cell_custom_objects(self, engine, merge_cells, ext):
11781178
expected.index = expected.index.astype(np.float64)
11791179
tm.assert_frame_equal(expected, result)
11801180

1181+
@pytest.mark.parametrize('dtype', [None, object])
1182+
def test_raise_when_saving_timezones(self, engine, ext, dtype,
1183+
tz_aware_fixture):
1184+
# GH 27008, GH 7056
1185+
tz = tz_aware_fixture
1186+
data = pd.Timestamp('2019', tz=tz)
1187+
df = DataFrame([data], dtype=dtype)
1188+
with pytest.raises(ValueError, match="Excel does not support"):
1189+
df.to_excel(self.path)
1190+
1191+
data = data.to_pydatetime()
1192+
df = DataFrame([data], dtype=dtype)
1193+
with pytest.raises(ValueError, match="Excel does not support"):
1194+
df.to_excel(self.path)
1195+
11811196

11821197
class TestExcelWriterEngineTests:
11831198

0 commit comments

Comments
 (0)