Skip to content

Commit acb2362

Browse files
committed
BUG/API: cast to nanos before writing datetimes to JSON
1 parent a505423 commit acb2362

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

pandas/core/arrays/datetimelike.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2342,6 +2342,9 @@ def _with_freq(self, freq) -> Self:
23422342

23432343
def _values_for_json(self) -> np.ndarray:
23442344
# Small performance bump vs the base class which calls np.asarray(self)
2345+
if self.unit != "ns":
2346+
# GH#55827
2347+
return self.as_unit("ns")._values_for_json()
23452348
if isinstance(self.dtype, np.dtype):
23462349
return self._ndarray
23472350
return super()._values_for_json()

pandas/tests/io/json/test_pandas.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,12 +132,6 @@ def test_frame_non_unique_index_raises(self, orient):
132132
],
133133
)
134134
def test_frame_non_unique_columns(self, orient, data, request):
135-
if isinstance(data[0][0], Timestamp) and orient == "split":
136-
mark = pytest.mark.xfail(
137-
reason="GH#55827 non-nanosecond dt64 fails to round-trip"
138-
)
139-
request.applymarker(mark)
140-
141135
df = DataFrame(data, index=[1, 2], columns=["x", "x"])
142136

143137
expected_warning = None
@@ -159,10 +153,14 @@ def test_frame_non_unique_columns(self, orient, data, request):
159153
# in milliseconds; these are internally stored in nanosecond,
160154
# so divide to get where we need
161155
# TODO: a to_epoch method would also solve; see GH 14772
162-
expected.isetitem(0, expected.iloc[:, 0].astype(np.int64) // 1000000)
156+
dta = expected.iloc[:, 0]._values
157+
dta = dta.as_unit("ns") # GH#55827
158+
expected.isetitem(0, dta.astype(np.int64) // 1_000_000)
163159
elif orient == "split":
164160
expected = df
165161
expected.columns = ["x", "x.1"]
162+
if expected["x"].dtype.kind == "M":
163+
expected["x"] = expected["x"].astype("M8[ns]") # GH#55827
166164

167165
tm.assert_frame_equal(result, expected)
168166

0 commit comments

Comments
 (0)