This is an automated email from the ASF dual-hosted git repository.

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 24545da7 [SPARK-61340][CONNECT][PYTHON] Send datetime literals as 
TIMESTAMP_NTZ when the session prefers it, in the Python client as PySpark does
24545da7 is described below

commit 24545da7577d6404342cf95bd8d6f089d107af0c
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 17:36:12 2026 +0900

    [SPARK-61340][CONNECT][PYTHON] Send datetime literals as TIMESTAMP_NTZ when 
the session prefers it, in the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61340](https://issues.apache.org/jira/browse/SPARK-61340): a 
datetime literal of the Python client is a TIMESTAMP_NTZ when the session 
prefers it, as PySpark's is.
    
    - In `crates/pyspark-rs/src/functions.rs`, `scalar_literal` reads 
`pyspark.sql.utils.is_timestamp_ntz_preferred()` for each datetime literal, as 
PySpark's `LiteralExpression._infer_type` does.
    - When it is true, the literal is a TIMESTAMP_NTZ of the wall clock: 
`calendar.timegm` of the time tuple, as `TimestampNTZType.toInternal` takes it, 
also for an aware datetime. Otherwise it is a TIMESTAMP of the instant, as 
before.
    - This covers every literal path: `lit`, Column comparisons, `isin`, 
`when`, the elements of `lit([...])`, and SQL args.
    
    ### Why are the changes needed?
    
    Under `spark.sql.timestampType=TIMESTAMP_NTZ`, every datetime literal was a 
TIMESTAMP of its instant. With a client zone other than the session's (here a 
client in Asia/Seoul and a UTC session):
    - `df.filter(col("t") == datetime(2020, 6, 1, 12))` on a TIMESTAMP_NTZ 
column matched 0 rows; PySpark matches 1. `isin` behaved the same.
    - `spark.sql("SELECT CAST(:t AS STRING)", args={"t": datetime(2020, 6, 1, 
12)})` gave `2020-06-01 03:00:00`; PySpark gives `12:00:00`.
    - `when(...)` and `lit([...])` were `timestamp` and `array<timestamp>`; 
PySpark gives `timestamp_ntz` and `array<timestamp_ntz>`.
    
    The drop-in's own `createDataFrame` already followed the conf.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Python client: under `spark.sql.timestampType=TIMESTAMP_NTZ`, 
datetime literals are TIMESTAMP_NTZ values of their wall clock, as in PySpark. 
As in PySpark, a datetime literal reads the conf of the active session.
    
    ### How was this patch tested?
    
    - Offline (`python/tests/test_dropin_offline.py`): 
`test_datetime_literals_follow_the_preferred_timestamp_type_as_pyspark`. Naive 
and aware datetimes give TIMESTAMP_NTZ literals of their wall clock under the 
conf, and TIMESTAMP literals of the instant without it. It fails without the 
change.
    - Live (`python/tests/test_dropin_e2e.py`): 
`test_datetime_literals_follow_the_preferred_timestamp_type_as_pyspark`.
      - Under the conf and a client in Asia/Seoul: a filter, `isin`, SQL args, 
`when` and `lit([...])` give PySpark's results.
      - Once the conf is unset, the literal is a TIMESTAMP again.
      - It fails without the change.
    - The reviewer's probes against official PySpark 4.3.0 (TZ=Asia/Seoul, UTC 
session) now match: no differing line, from 8 before.
    - Checks:
      - the lib tests (716 passed);
      - the build of all tests (also `wasm-udf`, `datafusion,polars`) without 
warnings;
      - `cargo fmt --all --check`, and clippy with no diagnostics on the 
changed lines;
      - the offline Python suites (2980 passed, 8 skipped);
      - the live drop-in, Arrow and ML suites against a local Spark 4.3.0 
server (255 passed).
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #463 from HyukjinKwon/s16-ntz-literals.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/functions.rs  | 30 ++++++++++++++++++++++++++++++
 python/tests/test_dropin_e2e.py     | 32 ++++++++++++++++++++++++++++++++
 python/tests/test_dropin_offline.py | 28 ++++++++++++++++++++++++++++
 3 files changed, 90 insertions(+)

diff --git a/crates/pyspark-rs/src/functions.rs 
b/crates/pyspark-rs/src/functions.rs
index 7fde16cf..d73afd28 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -561,6 +561,24 @@ fn numpy_scalar_literal(obj: &Bound<'_, PyAny>) -> 
PyResult<Option<LiteralExpres
 /// `decimal.Decimal`, `bytes`/`bytearray`). Returns `None` if `obj` is not 
one of them,
 /// so the caller falls through to the primitive int/float/str/bool checks. 
Kept in sync
 /// with `session::py_to_value` so `lit(..)` and `createDataFrame(..)` encode 
identically.
+/// The microseconds of the wall clock of a datetime, naive or aware, as 
PySpark's
+/// `TimestampNTZType.toInternal` takes them: `calendar.timegm` of its own 
time tuple, whatever
+/// its zone. A pandas Timestamp is taken as the datetime it stands for, as 
for a TIMESTAMP.
+fn wall_clock_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
+    let py = obj.py();
+    let normalized = if obj.hasattr("to_pydatetime").unwrap_or(false) {
+        obj.call_method0("to_pydatetime")?
+    } else {
+        obj.clone()
+    };
+    let seconds: i64 = py
+        .import("calendar")?
+        .call_method1("timegm", (normalized.call_method0("timetuple")?,))?
+        .extract()?;
+    let micros: i64 = normalized.getattr("microsecond")?.extract()?;
+    Ok(seconds * 1_000_000 + micros)
+}
+
 fn scalar_literal(obj: &Bound<'_, PyAny>) -> 
PyResult<Option<LiteralExpression>> {
     let py = obj.py();
 
@@ -584,6 +602,18 @@ fn scalar_literal(obj: &Bound<'_, PyAny>) -> 
PyResult<Option<LiteralExpression>>
     if let Ok(dt_mod) = py.import("datetime") {
         let datetime_cls = dt_mod.getattr("datetime")?;
         if obj.is_instance(&datetime_cls)? {
+            // As PySpark's `LiteralExpression._infer_type`: a TIMESTAMP_NTZ 
of the wall clock
+            // when the active session prefers it (`spark.sql.timestampType`), 
which PySpark reads
+            // for each datetime literal, else a TIMESTAMP of the instant.
+            if py
+                .import("pyspark.sql.utils")?
+                .call_method0("is_timestamp_ntz_preferred")?
+                .is_truthy()?
+            {
+                return 
Ok(Some(LiteralExpression::TimestampNtz(wall_clock_micros(
+                    obj,
+                )?)));
+            }
             // Shared with session::py_to_value so lit() and createDataFrame() 
agree (a pandas
             // Timestamp's .timestamp() treats a naive value as UTC; normalize 
it first).
             let micros = crate::session::datetime_to_micros(obj)?;
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 9e2a51e8..e05d5a4a 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3423,6 +3423,38 @@ for name, value in values:
     ]
 
 
+def 
test_datetime_literals_follow_the_preferred_timestamp_type_as_pyspark(session):
+    # As PySpark under spark.sql.timestampType=TIMESTAMP_NTZ: a datetime 
literal is a
+    # TIMESTAMP_NTZ of its wall clock, so it matches the TIMESTAMP_NTZ values 
of createDataFrame,
+    # also when the zone of the client is not that of the session; else it is 
a TIMESTAMP.
+    if not hasattr(time, "tzset"):
+        pytest.skip("time.tzset is not available")
+    value = datetime(2020, 6, 1, 12)
+    zone = os.environ.get("TZ")
+    os.environ["TZ"] = "Asia/Seoul"
+    time.tzset()
+    session.conf.set("spark.sql.timestampType", "TIMESTAMP_NTZ")
+    try:
+        df = session.createDataFrame([(value,)], ["t"])
+        assert df.schema.simpleString() == "struct<t:timestamp_ntz>"
+        assert df.filter(F.col("t") == value).count() == 1
+        assert df.filter(F.col("t").isin(value)).count() == 1
+        assert session.sql(
+            "SELECT CAST(:t AS STRING) AS t", args={"t": value}).first().t == 
"2020-06-01 12:00:00"
+        assert session.range(1).select(
+            F.when(F.lit(True), value).alias("w"), F.lit([value]).alias("a"),
+        ).schema.simpleString() == 
"struct<w:timestamp_ntz,a:array<timestamp_ntz>>"
+    finally:
+        session.conf.unset("spark.sql.timestampType")
+        if zone is None:
+            del os.environ["TZ"]
+        else:
+            os.environ["TZ"] = zone
+        time.tzset()
+    assert 
session.range(1).select(F.lit(value).alias("t")).schema.simpleString() == (
+        "struct<t:timestamp>")
+
+
 def test_window_frames_return_the_rows_of_pyspark(session):
     # As PySpark's: a range frame of a boundary out of the range of an int, 
which was
     # truncated, and the frames of the bounds of -sys.maxsize and sys.maxsize, 
unbounded.
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 97809e27..d56187b4 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -15005,6 +15005,34 @@ def 
test_datetime_literals_are_exact_micros_as_pyspark(mock_connect, monkeypatch
         time.tzset()
 
 
+def 
test_datetime_literals_follow_the_preferred_timestamp_type_as_pyspark(mock_connect):
+    # As PySpark's LiteralExpression._infer_type, which reads 
spark.sql.timestampType for each
+    # datetime literal: under TIMESTAMP_NTZ a datetime is a TIMESTAMP_NTZ of 
its wall clock (that
+    # of an aware datetime too, as TimestampNTZType.toInternal takes it), else 
a TIMESTAMP of the
+    # instant.
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+
+    def literal(column):
+        spark.range(1).select(column).collect()
+        # Project.expressions=3; Expression.literal=1; Literal.timestamp=17, 
timestamp_ntz=18.
+        plan = 
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+        expression = 
parse_message(parse_message(parse_message(plan)[3][0])[3][0])
+        return parse_message(expression[1][0])
+
+    seoul = datetime.timezone(datetime.timedelta(hours=9))
+    naive = datetime.datetime(2020, 6, 1, 12, 0, 0, 5)
+    aware = naive.replace(tzinfo=seoul)
+    wall = 1591012800000005
+    service.confs = {"spark.sql.timestampType": "TIMESTAMP_NTZ"}
+    assert literal(F.lit(naive)) == {18: [wall]}
+    assert literal(F.lit(aware)) == {18: [wall]}
+    service.confs = {"spark.sql.timestampType": "TIMESTAMP_LTZ"}
+    assert 17 in literal(F.lit(naive))
+    assert literal(F.lit(aware)) == {17: [wall - 9 * 3600 * 1_000_000]}
+
+
 def test_lit_errors_as_pyspark():
     np = pytest.importorskip("numpy")
     from pyspark.errors import PySparkTypeError, PySparkValueError


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to