Skip to content

Commit 40b82ea

Browse files
mroeschkeMatt Roeschke
and
Matt Roeschke
authored
BUG: to_sql no longer raises an AttributeError when saving an OBB date (#33140)
Co-authored-by: Matt Roeschke <[email protected]>
1 parent bdf969c commit 40b82ea

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

doc/source/whatsnew/v1.1.0.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,7 @@ I/O
405405
- Bug in :meth:`read_csv` was causing a segfault when there were blank lines between the header and data rows (:issue:`28071`)
406406
- Bug in :meth:`read_csv` was raising a misleading exception on a permissions issue (:issue:`23784`)
407407
- Bug in :meth:`read_csv` was raising an ``IndexError`` when header=None and 2 extra data columns
408-
408+
- Bug in :meth:`DataFrame.to_sql` where an ``AttributeError`` was raised when saving an out of bounds date (:issue:`26761`)
409409

410410
Plotting
411411
^^^^^^^^

pandas/io/sql.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -978,7 +978,8 @@ def _sqlalchemy_type(self, col):
978978
return TIMESTAMP(timezone=True)
979979
except AttributeError:
980980
# The column is actually a DatetimeIndex
981-
if col.tz is not None:
981+
# GH 26761 or an Index with date-like data e.g. 9999-01-01
982+
if getattr(col, "tz", None) is not None:
982983
return TIMESTAMP(timezone=True)
983984
return DateTime
984985
if col_type == "timedelta64":

pandas/tests/io/test_sql.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1480,6 +1480,14 @@ def test_datetime_with_timezone_roundtrip(self):
14801480
result["A"] = to_datetime(result["A"])
14811481
tm.assert_frame_equal(result, expected)
14821482

1483+
def test_out_of_bounds_datetime(self):
1484+
# GH 26761
1485+
data = pd.DataFrame({"date": datetime(9999, 1, 1)}, index=[0])
1486+
data.to_sql("test_datetime_obb", self.conn, index=False)
1487+
result = sql.read_sql_table("test_datetime_obb", self.conn)
1488+
expected = pd.DataFrame([pd.NaT], columns=["date"])
1489+
tm.assert_frame_equal(result, expected)
1490+
14831491
def test_naive_datetimeindex_roundtrip(self):
14841492
# GH 23510
14851493
# Ensure that a naive DatetimeIndex isn't converted to UTC

0 commit comments

Comments
 (0)