diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 865996bdf8892..a24c32ff213b9 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -269,6 +269,7 @@ Other Deprecations - Deprecated allowing non-keyword arguments in :meth:`Series.to_markdown` except ``buf``. (:issue:`57280`) - Deprecated allowing non-keyword arguments in :meth:`Series.to_string` except ``buf``. (:issue:`57280`) - Deprecated behavior of :meth:`Series.dt.to_pytimedelta`, in a future version this will return a :class:`Series` containing python ``datetime.timedelta`` objects instead of an ``ndarray`` of timedelta; this matches the behavior of other :meth:`Series.dt` properties. (:issue:`57463`) +- Deprecated converting object-dtype columns of ``datetime.datetime`` objects to datetime64 when writing to stata (:issue:`56536`) - Deprecated parameter ``method`` in :meth:`DataFrame.reindex_like` / :meth:`Series.reindex_like` (:issue:`58667`) - Deprecated using ``epoch`` date format in :meth:`DataFrame.to_json` and :meth:`Series.to_json`, use ``iso`` instead. (:issue:`57063`) - diff --git a/pandas/io/stata.py b/pandas/io/stata.py index b87ec94b85bb0..64932fe913cf3 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -393,6 +393,14 @@ def parse_dates_safe( d["days"] = np.asarray(diff).astype("m8[D]").view("int64") elif infer_dtype(dates, skipna=False) == "datetime": + warnings.warn( + # GH#56536 + "Converting object-dtype columns of datetimes to datetime64 when " + "writing to stata is deprecated. Call " + "`df=df.infer_objects(copy=False)` before writing to stata instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) if delta: delta = dates._values - stata_epoch diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index d5134a3e3afd0..22fd38ac63483 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -957,7 +957,12 @@ def test_big_dates(self, datapath, temp_file): # {c : c[-2:] for c in columns} path = temp_file expected.index.name = "index" - expected.to_stata(path, convert_dates=date_conversion) + msg = ( + "Converting object-dtype columns of datetimes to datetime64 " + "when writing to stata is deprecated" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + expected.to_stata(path, convert_dates=date_conversion) written_and_read_again = self.read_dta(path) tm.assert_frame_equal(