Skip to content

Commit 0913ed0

Browse files
ryankarlosjreback
authored andcommitted
DEPR: Deprecate pandas.datetime (pandas-dev#30489)
1 parent 9871bdd commit 0913ed0

File tree

11 files changed

+72
-26
lines changed

11 files changed

+72
-26
lines changed

doc/source/whatsnew/v1.0.0.rst

+3
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,9 @@ Other enhancements
225225
- :meth:`DataFrame.drop_duplicates` has gained ``ignore_index`` keyword to reset index (:issue:`30114`)
226226
- Added new writer for exporting Stata dta files in version 118, ``StataWriter118``. This format supports exporting strings containing Unicode characters (:issue:`23573`)
227227
- :meth:`Series.map` now accepts ``collections.abc.Mapping`` subclasses as a mapper (:issue:`29733`)
228+
- The ``pandas.datetime`` class is now deprecated. Import from ``datetime`` instead (:issue:`30296`)
229+
230+
228231

229232
Build Changes
230233
^^^^^^^^^^^^^

pandas/__init__.py

+39-2
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,6 @@
3939
"the C extensions first."
4040
)
4141

42-
from datetime import datetime
43-
4442
from pandas._config import (
4543
get_option,
4644
set_option,
@@ -210,6 +208,19 @@ class Panel:
210208

211209
return Panel
212210

211+
elif name == "datetime":
212+
warnings.warn(
213+
"The pandas.datetime class is deprecated "
214+
"and will be removed from pandas in a future version. "
215+
"Import from datetime module instead.",
216+
FutureWarning,
217+
stacklevel=2,
218+
)
219+
220+
from datetime import datetime as dt
221+
222+
return dt
223+
213224
elif name == "np":
214225

215226
warnings.warn(
@@ -264,13 +275,39 @@ def __getattr__(self, item):
264275
FutureWarning,
265276
stacklevel=2,
266277
)
278+
267279
try:
268280
return getattr(self.np, item)
269281
except AttributeError:
270282
raise AttributeError(f"module numpy has no attribute {item}")
271283

272284
np = __numpy()
273285

286+
class __Datetime:
287+
def __init__(self):
288+
from datetime import datetime as dt
289+
290+
self.datetime = dt
291+
292+
def __getattr__(self, item):
293+
import warnings
294+
295+
warnings.warn(
296+
"The pandas.datetime class is deprecated "
297+
"and will be removed from pandas in a future version. "
298+
"Import from datetime instead.",
299+
FutureWarning,
300+
stacklevel=2,
301+
)
302+
303+
try:
304+
return getattr(self.datetime, item)
305+
except AttributeError:
306+
raise AttributeError(f"module datetime has no attribute {item}")
307+
308+
datetime = __Datetime().datetime
309+
310+
274311
# module level doc-string
275312
__doc__ = """
276313
pandas - a powerful data analysis and manipulation library for Python

pandas/tests/api/test_api.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ class TestPDApi(Base):
9292
]
9393
if not compat.PY37:
9494
classes.extend(["Panel", "SparseSeries", "SparseDataFrame"])
95-
deprecated_modules.append("np")
95+
deprecated_modules.extend(["np", "datetime"])
9696

9797
# these are already deprecated; awaiting removal
9898
deprecated_classes: List[str] = []
@@ -101,7 +101,7 @@ class TestPDApi(Base):
101101
deprecated_classes_in_future: List[str] = []
102102

103103
# external modules exposed in pandas namespace
104-
modules = ["datetime"]
104+
modules: List[str] = []
105105

106106
# top-level functions
107107
funcs = [
@@ -232,11 +232,23 @@ def test_depr(self):
232232
with tm.assert_produces_warning(FutureWarning):
233233
if compat.PY37:
234234
getattr(pd, depr)
235+
elif depr == "datetime":
236+
deprecated = getattr(pd, "__Datetime")
237+
deprecated().__getattr__(dir(pd.datetime)[-1])
235238
else:
236239
deprecated = getattr(pd, depr)
237240
deprecated.__getattr__(dir(deprecated)[-1])
238241

239242

243+
def test_datetime():
244+
from datetime import datetime
245+
import warnings
246+
247+
with warnings.catch_warnings():
248+
warnings.simplefilter("ignore", FutureWarning)
249+
assert datetime(2015, 1, 2, 0, 0) == pd.datetime(2015, 1, 2, 0, 0)
250+
251+
240252
def test_np():
241253
import numpy as np
242254
import warnings

pandas/tests/dtypes/test_common.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from datetime import datetime
12
from typing import List
23

34
import numpy as np
@@ -490,7 +491,7 @@ def test_is_numeric_v_string_like():
490491

491492

492493
def test_is_datetimelike_v_numeric():
493-
dt = np.datetime64(pd.datetime(2017, 1, 1))
494+
dt = np.datetime64(datetime(2017, 1, 1))
494495

495496
assert not com.is_datetimelike_v_numeric(1, 1)
496497
assert not com.is_datetimelike_v_numeric(dt, dt)

pandas/tests/frame/indexing/test_indexing.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1146,18 +1146,18 @@ def test_setitem_mixed_datetime(self):
11461146
{
11471147
"a": [0, 0, 0, 0, 13, 14],
11481148
"b": [
1149-
pd.datetime(2012, 1, 1),
1149+
datetime(2012, 1, 1),
11501150
1,
11511151
"x",
11521152
"y",
1153-
pd.datetime(2013, 1, 1),
1154-
pd.datetime(2014, 1, 1),
1153+
datetime(2013, 1, 1),
1154+
datetime(2014, 1, 1),
11551155
],
11561156
}
11571157
)
11581158
df = pd.DataFrame(0, columns=list("ab"), index=range(6))
11591159
df["b"] = pd.NaT
1160-
df.loc[0, "b"] = pd.datetime(2012, 1, 1)
1160+
df.loc[0, "b"] = datetime(2012, 1, 1)
11611161
df.loc[1, "b"] = 1
11621162
df.loc[[2, 3], "b"] = "x", "y"
11631163
A = np.array(

pandas/tests/groupby/test_groupby.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -1729,9 +1729,7 @@ def test_pivot_table_values_key_error():
17291729
# This test is designed to replicate the error in issue #14938
17301730
df = pd.DataFrame(
17311731
{
1732-
"eventDate": pd.date_range(
1733-
pd.datetime.today(), periods=20, freq="M"
1734-
).tolist(),
1732+
"eventDate": pd.date_range(datetime.today(), periods=20, freq="M").tolist(),
17351733
"thename": range(0, 20),
17361734
}
17371735
)

pandas/tests/indexes/datetimes/test_constructors.py

+2-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from datetime import timedelta
1+
from datetime import datetime, timedelta
22
from functools import partial
33
from operator import attrgetter
44

@@ -10,15 +10,7 @@
1010
from pandas._libs.tslibs import OutOfBoundsDatetime, conversion
1111

1212
import pandas as pd
13-
from pandas import (
14-
DatetimeIndex,
15-
Index,
16-
Timestamp,
17-
date_range,
18-
datetime,
19-
offsets,
20-
to_datetime,
21-
)
13+
from pandas import DatetimeIndex, Index, Timestamp, date_range, offsets, to_datetime
2214
from pandas.core.arrays import DatetimeArray, period_array
2315
import pandas.util.testing as tm
2416

pandas/tests/indexes/datetimes/test_misc.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import calendar
2+
from datetime import datetime
23
import locale
34
import unicodedata
45

56
import numpy as np
67
import pytest
78

89
import pandas as pd
9-
from pandas import DatetimeIndex, Index, Timestamp, date_range, datetime, offsets
10+
from pandas import DatetimeIndex, Index, Timestamp, date_range, offsets
1011
import pandas.util.testing as tm
1112

1213

pandas/tests/indexing/test_iloc.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
""" test positional based indexing with iloc """
22

3+
from datetime import datetime
34
from warnings import catch_warnings, simplefilter
45

56
import numpy as np
@@ -122,7 +123,7 @@ def check(result, expected):
122123
[
123124
([slice(None), ["A", "D"]]),
124125
(["1", "2"], slice(None)),
125-
([pd.datetime(2019, 1, 1)], slice(None)),
126+
([datetime(2019, 1, 1)], slice(None)),
126127
],
127128
)
128129
def test_iloc_non_integer_raises(self, index, columns, index_vals, column_vals):

pandas/tests/io/excel/test_writers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ def test_read_excel_parse_dates(self, ext):
252252
res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0)
253253
tm.assert_frame_equal(df, res)
254254

255-
date_parser = lambda x: pd.datetime.strptime(x, "%m/%d/%Y")
255+
date_parser = lambda x: datetime.strptime(x, "%m/%d/%Y")
256256
res = pd.read_excel(
257257
pth, parse_dates=["date_strings"], date_parser=date_parser, index_col=0
258258
)

pandas/tests/io/sas/test_sas7bdat.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from datetime import datetime
12
import io
23
import os
34
from pathlib import Path
@@ -23,7 +24,7 @@ def setup_method(self, datapath):
2324
for j in 1, 2:
2425
fname = os.path.join(self.dirpath, f"test_sas7bdat_{j}.csv")
2526
df = pd.read_csv(fname)
26-
epoch = pd.datetime(1960, 1, 1)
27+
epoch = datetime(1960, 1, 1)
2728
t1 = pd.to_timedelta(df["Column4"], unit="d")
2829
df["Column4"] = epoch + t1
2930
t2 = pd.to_timedelta(df["Column12"], unit="d")

0 commit comments

Comments
 (0)