Skip to content

[Data] Fix write_json for non-nanosecond timestamps and durations - #68007

Merged
owenowenisme merged 1 commit into
ray-project:masterfrom
hzmsh:fix/write-json-non-ns-timestamps
Nov 27, 2026
Merged

owenowenisme merged 1 commit into
ray-project:masterfrom
hzmsh:fix/write-json-non-ns-timestamps

Conversation

@hzmsh

@hzmsh hzmsh commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Fixes #42920

Summary

On pandas < 3, write_json treats non-nanosecond timestamp (without time zone) and duration columns as nanoseconds, so 2024-01-01 12:00:00 read from Parquet (timestamp[us]) is written as 1704110400, which reads back as 1970-01-20, instead of 1704110400000. This PR converts those columns to the output unit before calling to_json() (integers in date_unit for the default epoch output), so the written values are correct.

Before

Ray's write_json hands each block to pandas: JSONDatasink.write_block_to_file calls block.to_pandas().to_json(...). In pandas < 3, to_json() itself treats non-nanosecond timestamps (without time zone) and durations as nanoseconds (pandas-dev/pandas#55827, fixed in pandas 3.0).

Ray requires pandas >= 2.2.3 with no upper bound, so anyone on pandas 2.2.3 to 2.3.x hits this bug. pip install "ray[data]" installs pandas 3 on Python 3.11+, but on Python 3.10, which Ray still supports, it installs pandas 2.3.3 (pandas 3 needs Python >= 3.11). Ray's own lock file, python/requirements_compiled.txt, also pins pandas==2.3.3, so anyone installing with it hits this bug.

For example, writing a timestamp[us] column, the usual type in Parquet files:

ds = ray.data.from_arrow(
    pa.table({"ts": pa.array([datetime(2024, 1, 1, 12)], pa.timestamp("us"))})
)
ds.write_json(path)  # {"ts":1704110400}, which reads back as 1970-01-20

The same happens with timestamp[s] (the usual type from read_json) and with durations. For 2024-01-01 12:00:00 and a 90-second duration, this is what is written today:

Column type Written today Correct
timestamp[s] 1704 (1970-01-01 00:00:01.704) 1704110400000
timestamp[us] 1704110400 (1970-01-20) 1704110400000
timestamp[ns] 1704110400000 1704110400000
duration[s] 0 90000
duration[s] with date_format="iso" "P0DT0H0M0.000000090S" (90 ns) "P0DT0H1M30S"

Also, setting date_unit doesn't help users avoid it. For example, with date_unit="s", 2024-01-01 12:00:00 (timestamp[s]) should be written as 1704110400, but it is written as 1. This is because to_json() still reads the value as nanoseconds (1704110400 ns is about 1.7 seconds) and only then converts it to seconds. Both Arrow blocks and pandas blocks are affected, so no write_json argument gives correct epoch numbers for these columns.

After

To fix this, write_json now first calls _fix_non_nanosecond_columns on a shallow copy of the DataFrame, and then calls to_json(). This step only runs on pandas < 3. What it does depends on the output format:

  1. Epoch numbers (the default):
  2. ISO strings (date_format="iso"):
    • pandas 2 already writes ISO timestamps correctly, so timestamp columns are left alone.
    • Only top-level non-nanosecond durations are converted to nanoseconds.

Everything else is unchanged.

One behavior changes: when the target unit is nanoseconds (durations with date_format="iso", or any column with date_unit="ns"), values outside the int64 nanosecond range (about 292 years, so dates outside 1677-2262 such as 9999-12-31) now raise ArrowInvalid instead of being written as wrong numbers.

This PR doesn't cover timestamps or durations inside list columns or dictionary-encoded columns; those are still written in the wrong unit. Happy to handle these in a follow-up PR if needed.

flowchart TB
    subgraph Before
        subgraph BS[Subsystem: IO]
            subgraph BC[Component: JSONDatasink.write_block_to_file]
                direction LR
                B1["block.to_pandas()"] --> B2["df.to_json()<br/>timestamp[us] 2024-01-01 12:00:00 -> 1704110400"]
            end
        end
    end
    subgraph After
        subgraph AS[Subsystem: IO]
            subgraph AC[Component: JSONDatasink.write_block_to_file]
                direction LR
                A1["block.to_pandas()"] --> A3["_fix_non_nanosecond_columns<br/>(pandas < 3)"] --> A2["df.to_json()<br/>timestamp[us] 2024-01-01 12:00:00 -> 1704110400000"]
            end
        end
    end
    Before ~~~ After
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A3 added
    class A2 changed
Loading

Subsystems

IO (_internal/datasource/json_datasink.py)

Testing

To check this, I added two tests to datasource/test_json.py, each run with an Arrow block and a pandas block:

  • test_json_write_non_nanosecond_temporal_columns: s/ms/us/ns timestamps, a us timestamp with a sub-millisecond part, a UTC timestamp, and s/ms/us/ns durations, each with a null row, written with the default settings and with date_unit="s".
  • test_json_write_date_outside_nanosecond_range: 9999-12-31 and a duration, written with the default settings, date_format="iso" and orient="table".

On master, 8 of the 10 cases fail. The other 2 are the orient="table" cases (a to_json layout that writes dates as ISO strings), which pass on master too; they check that this layout is left alone.

I also ran pytest python/ray/data/tests/datasource/test_json.py: 74 passed on both pandas 2.3.3 and pandas 2.2.3 (Ray's minimum).

Why this is not a duplicate

On 2026-11-07 and again on 2026-11-09 I searched open and closed issues and PRs for write_json with timestamp/datetime/epoch, JSONDatasink, to_json date_unit, 55827 and "non-nanosecond". No PR addresses #42920, and json_datasink.py is the only place Ray Data calls pandas to_json.

AI assistance

AI use: I worked with Claude Code (claude opus 5.5 (high)). Together we identified the root cause, wrote the fix and tests, and ran the tests. It also helped turn my thoughts into this description. I also used gemini argon (high) for an additional review.

On pandas < 3, DataFrame.to_json() treats non-nanosecond timestamps and
durations as nanoseconds (pandas-dev/pandas#55827), so write_json wrote
a timestamp[us] 2024-01-01 12:00:00 as 1704110400, which reads back as
1970.

Before to_json(), cast these columns with pyarrow to integers in
date_unit for epoch output, following pandas 3, so dates outside the
nanosecond range such as 9999-12-31 still write. For ISO output, cast
only durations to nanoseconds. orient="table" is already correct and
is left alone. Both Arrow and pandas blocks are covered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: hzmsh <[email protected]>
@hzmsh
hzmsh requested a review from a team as a code owner November 10, 2026 03:54

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a workaround in JSONDatasink for pandas < 3, addressing an issue where non-nanosecond timestamps and durations are incorrectly written as nanoseconds. It adds a helper function _fix_non_nanosecond_columns to cast these columns to the appropriate unit before writing, along with corresponding regression tests. The review feedback suggests a more robust way to convert pandas Series to PyArrow arrays using pyarrow.Table.from_pandas to avoid potential TypeError exceptions when dealing with chunked pd.ArrowDtype columns.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Nov 10, 2026
@hzmsh

hzmsh commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Hi @owenowenisme, could you please take a look at this when you have time? I noticed you reviewed the recent JSON read change (#66878), and this one fixes a bug on the JSON write side. Thanks!

@rayo5o rayo5o left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. The description says the fix follows pandas 3, so I used pandas 3's output as the reference and compared against it.

Setup: pandas 2.3.3 (the lock version) and pandas 3.0.6, pyarrow 26.0.0, each on the PR head (ba465e7) and the merge base (38af0c3). I called JSONDatasink.write_block_to_file on 12 small tables, each as an Arrow block, a pandas block, and an Arrow block with enable_arrow_backed_pandas_conversion=False, with 11 sets of to_json args (default, date_unit s/us/ns, date_format epoch/iso, iso with date_unit="s", orient split/columns/values/table). 396 outputs per run.

  • pandas 3: head and merge base write the same output in all 396, so the version gate does what it should.
  • pandas 2.3.3 with this PR vs pandas 3: 96 outputs go from wrong to matching pandas 3, and none that matched before stops matching. Also identical to pandas 3: tz-aware columns (including Asia/Taipei in us), timestamps and durations inside a struct, all-null and 0-row columns.
  • What still differs is what the description already lists (list and dictionary columns, date_unit="ns" past 2262 now raising), plus date32, where pandas 3 itself raises NotImplementedError: as_unit not implemented for date32[day].
  • The new tests: 8 fail on the merge base and pass on the head with pandas 2.3.3. The rest of test_json.py matches the description (2 httpserver errors are my env).
  • A 3-chunk column with an empty and an all-null chunk (Gemini's comment) also writes correctly.

@hzmsh

hzmsh commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Hi, a short status update: this PR still merges cleanly into master and CI is green. rayo5o also verified the fix on pandas 2.3.3 and 3.0.6 (thanks!). I notice that #68089 changes the same function in json_datasink.py, and I will rebase this PR if that one lands first. Whenever someone from the Data team has time, a review would be much appreciated.

@owenowenisme owenowenisme added the go add ONLY when ready to merge, run all tests label Nov 27, 2026
@owenowenisme
owenowenisme enabled auto-merge (squash) November 27, 2026 12:17
@owenowenisme
owenowenisme merged commit 976013d into ray-project:master Nov 27, 2026
8 checks passed
@hzmsh
hzmsh deleted the fix/write-json-non-ns-timestamps branch November 27, 2026 14:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] Ray writes corrupted datetime values to json

3 participants