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

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


The following commit(s) were added to refs/heads/master by this push:
     new b72a0b2a1a08 [SPARK-57836][SQL] Support nanosecond precision in 
to_timestamp, to_timestamp_ntz, to_timestamp_ltz and try_to_timestamp
b72a0b2a1a08 is described below

commit b72a0b2a1a0813ac49fab501ca3216a8fd4f01db
Author: Stevo Mitric <[email protected]>
AuthorDate: Mon Oct 26 08:49:39 2026 +0000

    [SPARK-57836][SQL] Support nanosecond precision in to_timestamp, 
to_timestamp_ntz, to_timestamp_ltz and try_to_timestamp
    
    ### What changes were proposed in this pull request?
    This PR adds an optional `precision` argument to `to_timestamp`, 
`to_timestamp_ntz`, `to_timestamp_ltz` and `try_to_timestamp`: 
`to_timestamp(timestamp_str, fmt, precision)`. A precision in [7, 9] parses up 
to 9 fractional digits into `TIMESTAMP_NTZ(p)` / `TIMESTAMP_LTZ(p)`, truncates 
the digits beyond `p`, and requires `spark.sql.timestampNanosTypes.enabled`. 
Precision 6 keeps the microsecond type and behaves like the two-argument form. 
The argument is validated like `current_timestamp(p)`.
    
    Without a precision, a nanosecond-precision input now keeps its precision 
instead of being narrowed to microseconds, e.g. `to_timestamp(TIMESTAMP_NTZ 
'2020-01-01 00:00:00.123456789')` returns `TIMESTAMP_LTZ(9)`.
    
    Main changes:
    - `GetTimestamp` parses a string into a nanosecond result in both the 
interpreted and codegen paths, using the nanosecond-aware `TimestampFormatter`, 
with the same ANSI, non-ANSI and `try_` error behavior as the microsecond path.
    - With a format, a DATE or timestamp input that is converted to or from a 
nanosecond type ignores the format and is converted like `CAST` in the session 
time zone, the same as without a format.
    - `to_timestamp` is now registered through an expression builder, like the 
other three functions.
    - The precision validator shared with `current_timestamp(p)` / `now(p)` / 
`localtimestamp(p)` now range-checks the full value, so a BIGINT precision such 
as 4294967305 is rejected instead of wrapping to 9.
    
    Known difference between precision 6 and 7-9: with a format, a DATE or 
other-family timestamp input at precision 6, like the two-argument form, keeps 
the existing behavior tracked by SPARK-52457. A DATE becomes midnight in the 
session time zone even for `TIMESTAMP_NTZ`, and a timestamp of the other family 
is not shifted by the zone. Precision 7-9 converts like `CAST`. In 
America/Los_Angeles, `to_timestamp_ntz(DATE '2020-01-01', 'yyyy', 6)` returns 
`2020-01-01 08:00:00` while `(..., 7) [...]
    
    A numeric input with a format is cast to a string and parsed at every 
precision, the same as the two-argument form since SPARK-59988.
    
    ### Why are the changes needed?
    Part of SPARK-56822. These functions are the SQL way to parse a string with 
a custom format, and today they always return microseconds. A nanosecond input 
is also silently truncated, even under ANSI mode.
    
    ### Does this PR introduce _any_ user-facing change?
    Yes. With `spark.sql.timestampNanosTypes.enabled` on, the three-argument 
form with precision 7-9 returns nanosecond timestamps, and a 
nanosecond-precision input keeps its precision. Regardless of the flag, the 
three-argument form accepts precision 6, wrong-arity errors for these functions 
now list `[1, 2, 3]`, `DESCRIBE FUNCTION to_timestamp` reports 
`ParseToTimestampExpressionBuilder`, and an out-of-range BIGINT precision in 
`current_timestamp(p)` / `now(p)` / `localtimestamp(p)` rai [...]
    
    ### How was this patch tested?
    - New `DateExpressionsSuite` cases for `GetTimestamp` with nanosecond 
results (both error modes, interpreted and codegen, LEGACY parser policy) and 
for the BIGINT precision check.
    - New `TimestampNanosFunctionsSuiteBase` tests, run with ANSI on and off, 
covering parsing, precision errors, nanosecond-input preservation, numeric 
input, CAST equivalence for DATE and timestamp inputs, and precision 6 matching 
the two-argument form.
    - New golden cases in `timestamp-ntz-nanos.sql` / `timestamp-ltz-nanos.sql`.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    Generated-by: Isaac
    
    Closes #59577 from stevomitric/stevomitric/nanos-to-timestamp.
    
    Authored-by: Stevo Mitric <[email protected]>
    Signed-off-by: Uros Bojanic <[email protected]>
---
 docs/sql-ref-datetime-pattern.md                   |   1 +
 .../expressions/DateTimeExpressionUtils.java       |  23 ++
 .../sql/catalyst/analysis/FunctionRegistry.scala   |   2 +-
 .../catalyst/expressions/datetimeExpressions.scala | 280 +++++++++++++++++----
 .../expressions/DateExpressionsSuite.scala         |  85 ++++++-
 .../sql-functions/sql-expression-schema.md         |   2 +-
 .../analyzer-results/timestamp-ltz-nanos.sql.out   | 115 +++++++++
 .../analyzer-results/timestamp-ntz-nanos.sql.out   | 137 ++++++++++
 .../sql-tests/inputs/timestamp-ltz-nanos.sql       |  25 ++
 .../sql-tests/inputs/timestamp-ntz-nanos.sql       |  24 ++
 .../sql-tests/results/timestamp-ltz-nanos.sql.out  | 140 +++++++++++
 .../sql-tests/results/timestamp-ntz-nanos.sql.out  | 164 ++++++++++++
 .../sql/TimestampNanosFunctionsSuiteBase.scala     | 192 +++++++++++++-
 13 files changed, 1137 insertions(+), 53 deletions(-)

diff --git a/docs/sql-ref-datetime-pattern.md b/docs/sql-ref-datetime-pattern.md
index 9ce91738bb49..8174a43c6816 100644
--- a/docs/sql-ref-datetime-pattern.md
+++ b/docs/sql-ref-datetime-pattern.md
@@ -71,6 +71,7 @@ The count of pattern letters determines the format.
   For parsing, the acceptable fraction length can be [1, the number of 
contiguous 'S'].
   For formatting, the fraction length would be padded to the number of 
contiguous 'S' with zeros.
   Spark supports datetime of micro-of-second precision, which has up to 6 
significant digits, but can parse nano-of-second with exceeded part truncated.
+  The preview nanosecond-precision types `TIMESTAMP_NTZ(p)`/`TIMESTAMP_LTZ(p)` 
keep up to `p` fractional digits, e.g. `to_timestamp(timestamp_str, fmt, p)`.
 
 - Year: The count of letters determines the minimum field width below which 
padding is used. If the count of letters is two, then a reduced two digit form 
is used. For printing, this outputs the rightmost two digits. For parsing, this 
will parse using the base value of 2000, resulting in a year within the range 
2000 to 2099 inclusive. If the count of letters is less than four (but not 
two), then the sign is only output for negative years. Otherwise, the sign is 
output if the pad width is [...]
 
diff --git 
a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/DateTimeExpressionUtils.java
 
b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/DateTimeExpressionUtils.java
index 8cde11c577d5..748644fc093a 100644
--- 
a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/DateTimeExpressionUtils.java
+++ 
b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/DateTimeExpressionUtils.java
@@ -31,6 +31,7 @@ import org.apache.spark.sql.catalyst.util.TimestampFormatter;
 import org.apache.spark.sql.errors.QueryExecutionErrors;
 import org.apache.spark.sql.types.Decimal;
 import org.apache.spark.unsafe.types.CalendarInterval;
+import org.apache.spark.unsafe.types.TimestampNanosVal;
 import org.apache.spark.unsafe.types.UTF8String;
 
 /**
@@ -167,6 +168,28 @@ public final class DateTimeExpressionUtils {
     }
   }
 
+  /**
+   * Nanosecond counterpart of {@link #parseToTimestampExact}: parses {@code 
input}
+   * to a TIMESTAMP_NTZ(precision) / TIMESTAMP_LTZ(precision) value, flooring 
the
+   * fraction to {@code precision}, with the same ANSI error translation.
+   */
+  public static TimestampNanosVal parseToTimestampNanosExact(
+      TimestampFormatter formatter,
+      String input,
+      int precision,
+      boolean forTimestampNTZ,
+      String suggestedFuncOnFail) {
+    try {
+      if (forTimestampNTZ) {
+        return formatter.parseWithoutTimeZoneNanos(input, precision);
+      } else {
+        return formatter.parseNanos(input, precision);
+      }
+    } catch (DateTimeException | ParseException e) {
+      throw QueryExecutionErrors.ansiDateTimeParseError(e, 
suggestedFuncOnFail);
+    }
+  }
+
   /**
    * Computes the first date after {@code startDate} that falls on the weekday
    * named by {@code dayOfWeek} for {@code NextDay} (next_day) in ANSI mode
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
index d7661eb360af..84e987a5a5b9 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
@@ -650,7 +650,7 @@ object FunctionRegistry {
     expressionBuilder("now", NowExpressionBuilder),
     expression[Quarter]("quarter"),
     expressionBuilder("second", SecondExpressionBuilder),
-    expression[ParseToTimestamp]("to_timestamp"),
+    expressionBuilder("to_timestamp", ParseToTimestampExpressionBuilder),
     expression[ParseToDate]("to_date"),
     expression[TimeDiff]("time_diff"),
     expression[ToTime]("to_time"),
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/datetimeExpressions.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/datetimeExpressions.scala
index a64610d25358..5ec46e3b9c67 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/datetimeExpressions.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/datetimeExpressions.scala
@@ -269,32 +269,37 @@ case class LocalTimestampNanos(precision: Int, 
timeZoneId: Option[String] = None
 }
 
 /**
- * Shared precision handling for the `current_timestamp(p)` / `now(p)` / 
`localtimestamp(p)`
- * expression builders.
+ * Shared precision handling for the `current_timestamp(p)` / `now(p)` / 
`localtimestamp(p)` and
+ * `to_timestamp*(str, fmt, p)` expression builders.
  */
 private[expressions] object CurrentTimestampPrecision {
   /**
-   * Validates the foldable integer precision argument `p` of a 
current-timestamp function and
+   * Validates the foldable integer precision argument `p` of a timestamp 
function and
    * returns it. `p == 6` selects the historical microsecond type; `p` in `[7, 
9]` selects the
    * nanosecond type (which requires `spark.sql.timestampNanosTypes.enabled`). 
Any other value is
    * rejected with `INVALID_TIMESTAMP_PRECISION`. The `typeName` 
(`TIMESTAMP_LTZ` / `TIMESTAMP_NTZ`)
    * is used in the precision / feature-flag error messages, matching the 
`TIMESTAMP(p)` type
-   * parser.
+   * parser. `paramIndex` is the 1-based position of the argument, used in 
type errors.
    */
-  def validate(funcName: String, precision: Expression, typeName: String): Int 
= {
+  def validate(
+      funcName: String,
+      precision: Expression,
+      typeName: String,
+      paramIndex: Int = 1): Int = {
     if (!precision.foldable) {
       throw QueryCompilationErrors.nonFoldableArgumentError(
         funcName, "precision", precision.dataType)
     }
     if (!precision.dataType.isInstanceOf[IntegralType]) {
       throw QueryCompilationErrors.unexpectedInputDataTypeError(
-        funcName, 1, IntegerType, precision)
+        funcName, paramIndex, IntegerType, precision)
     }
     val value = precision.eval()
     if (value == null) {
       throw QueryCompilationErrors.unexpectedNullError("precision", precision)
     }
-    val p = value.asInstanceOf[Number].intValue()
+    // Range-check the long value so a BIGINT precision can't wrap into range.
+    val p = value.asInstanceOf[Number].longValue()
     // Reject out-of-range precisions before the feature-flag check so the 
error is always
     // INVALID_TIMESTAMP_PRECISION, not FEATURE_NOT_ENABLED (mirrors the 
TIMESTAMP(p) type parser).
     if (p != 6 &&
@@ -304,7 +309,7 @@ private[expressions] object CurrentTimestampPrecision {
     if (p != 6) {
       DataTypeErrors.checkTimestampNanosTypesEnabled()
     }
-    p
+    p.toInt
   }
 }
 
@@ -1966,7 +1971,9 @@ case class UnixTimestamp(
 }
 
 /**
- * Gets a timestamp from a string or a date.
+ * Gets a timestamp from a string or a date. For a nanosecond 
`TIMESTAMP_NTZ(p)` /
+ * `TIMESTAMP_LTZ(p)` result `dataType`, only a string is accepted. It is 
parsed with up to 9
+ * fractional digits, truncated to `p`; [[ParseToTimestamp]] casts other 
inputs instead.
  */
 case class GetTimestamp(
     left: Expression,
@@ -1976,10 +1983,104 @@ case class GetTimestamp(
     timeZoneId: Option[String] = None,
     failOnError: Boolean = SQLConf.get.ansiEnabled) extends ToTimestamp {
 
-  override val forTimestampNTZ: Boolean = dataType == TimestampNTZType
+  override val forTimestampNTZ: Boolean = TimestampFamily.isNtz(dataType)
+
+  // The precision p in [7, 9] of a nanosecond result type; None for a 
microsecond one.
+  @transient private lazy val nanosPrecision: Option[Int] = dataType match {
+    case _: AnyTimestampNanoType => 
TimestampFamily.fractionalPrecision(dataType)
+    case _ => None
+  }
 
   override protected def downScaleFactor: Long = 1
 
+  override def inputTypes: Seq[AbstractDataType] = nanosPrecision match {
+    case None => super.inputTypes
+    case Some(_) => Seq.fill(2)(StringTypeWithCollation(supportsTrimCollation 
= true))
+  }
+
+  override def eval(input: InternalRow): Any = nanosPrecision match {
+    case None => super.eval(input)
+    case Some(precision) =>
+      val str = left.eval(input)
+      if (str == null) {
+        null
+      } else {
+        parseStringNanos(str.asInstanceOf[UTF8String], input, precision)
+      }
+  }
+
+  private def parseStringNanos(str: UTF8String, input: InternalRow, precision: 
Int): Any = {
+    val fmt = right.eval(input)
+    if (fmt == null) {
+      null
+    } else {
+      val formatter = formatterOption.getOrElse(getFormatter(fmt.toString))
+      if (failOnError) {
+        DateTimeExpressionUtils.parseToTimestampNanosExact(
+          formatter, str.toString, precision, forTimestampNTZ, 
suggestedFuncOnFail)
+      } else {
+        try {
+          if (forTimestampNTZ) {
+            formatter.parseWithoutTimeZoneNanos(str.toString, precision)
+          } else {
+            formatter.parseNanos(str.toString, precision)
+          }
+        } catch {
+          case e if isParseError(e) => null
+        }
+      }
+    }
+  }
+
+  override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = 
nanosPrecision match {
+    case None => super.doGenCode(ctx, ev)
+    case Some(precision) => nanosGenCode(ctx, ev, precision)
+  }
+
+  private def nanosGenCode(ctx: CodegenContext, ev: ExprCode, precision: Int): 
ExprCode = {
+    val utils = classOf[DateTimeExpressionUtils].getName
+    val parseMethod = if (forTimestampNTZ) "parseWithoutTimeZoneNanos" else 
"parseNanos"
+    def parseTimestampCode(formatterExpr: String, inputExpr: String): String = 
{
+      if (failOnError) {
+        s"""${ev.value} = $utils.parseToTimestampNanosExact(
+           |    $formatterExpr, $inputExpr, $precision,
+           |    $forTimestampNTZ, "$suggestedFuncOnFail");""".stripMargin
+      } else {
+        s"""
+           |try {
+           |  ${ev.value} = $formatterExpr.$parseMethod($inputExpr, 
$precision);
+           |} catch (java.time.DateTimeException e) {
+           |  ${ev.isNull} = true;
+           |} catch (java.text.ParseException e) {
+           |  ${ev.isNull} = true;
+           |}
+           |""".stripMargin
+      }
+    }
+    formatterOption.map { fmt =>
+      val df = classOf[TimestampFormatter].getName
+      val formatterName = ctx.addReferenceObj("formatter", fmt, df)
+      nullSafeCodeGen(ctx, ev, (datetimeStr, _) =>
+        parseTimestampCode(formatterName, s"$datetimeStr.toString()"))
+    }.getOrElse {
+      val zid = ctx.addReferenceObj("zoneId", zoneId, classOf[ZoneId].getName)
+      val tf = TimestampFormatter.getClass.getName.stripSuffix("$")
+      val ldf = LegacyDateFormats.getClass.getName.stripSuffix("$")
+      val timestampFormatter = ctx.freshName("timestampFormatter")
+      // Passes `forTimestampNTZ` like `getFormatter` in the interpreted path.
+      nullSafeCodeGen(ctx, ev, (string, format) =>
+        s"""
+           |$tf $timestampFormatter = $tf$$.MODULE$$.apply(
+           |  $format.toString(),
+           |  $zid,
+           |  $ldf$$.MODULE$$.SIMPLE_DATE_FORMAT(),
+           |  true,
+           |  $forTimestampNTZ);
+           |${parseTimestampCode(timestampFormatter, s"$string.toString()")}
+           |""".stripMargin)
+    }
+  }
+
   override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
     copy(timeZoneId = Some(timeZoneId))
 
@@ -1995,20 +2096,28 @@ case class GetTimestamp(
 /**
  * Parses a column to a timestamp without time zone based on the supplied 
format.
  */
-// scalastyle:off line.size.limit
+// scalastyle:off line.size.limit line.contains.tab
 @ExpressionDescription(
   usage = """
     _FUNC_(timestamp_str[, fmt]) - Parses the `timestamp_str` expression with 
the `fmt` expression
       to a timestamp without time zone. Returns null with invalid input. By 
default, it follows casting rules to
       a timestamp if the `fmt` is omitted.
+
+    _FUNC_(timestamp_str, fmt, precision) - Parses the `timestamp_str` 
expression with the `fmt` expression
+      to a timestamp without time zone with the given fractional-seconds 
precision. A precision in [7, 9] returns a
+      nanosecond-precision TIMESTAMP_NTZ(precision) and requires 
spark.sql.timestampNanosTypes.enabled to be true;
+      precision 6 returns the microsecond TIMESTAMP_NTZ.
   """,
   arguments = """
     Arguments:
       * timestamp_str - A string to be parsed to timestamp without time zone.
-        An expression that evaluates to a string, date, or timestamp.
+        An expression that evaluates to a string, date, or timestamp. A 
nanosecond-precision
+        timestamp keeps its precision if `precision` is omitted.
       * fmt - Timestamp format pattern to follow. See <a 
href="https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html";>Datetime
 Patterns</a> for valid
               date and time format patterns.
         An expression that evaluates to a string.
+      * precision - An optional integer literal, either 6 or a value in [7, 
9]. Fractional digits
+        beyond `precision` are truncated.
   """,
   examples = """
     Examples:
@@ -2016,39 +2125,45 @@ case class GetTimestamp(
        2016-12-31 00:12:00
       > SELECT _FUNC_('2016-12-31', 'yyyy-MM-dd');
        2016-12-31 00:00:00
+      > SET spark.sql.timestampNanosTypes.enabled=true;
+      spark.sql.timestampNanosTypes.enabled    true
+      > SELECT _FUNC_('2016-12-31 00:12:00.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 7);
+       2016-12-31 00:12:00.1234567
   """,
   group = "datetime_funcs",
   since = "3.4.0")
-// scalastyle:on line.size.limit
+// scalastyle:on line.size.limit line.contains.tab
 object ParseToTimestampNTZExpressionBuilder extends ExpressionBuilder {
-  override def build(funcName: String, expressions: Seq[Expression]): 
Expression = {
-    val numArgs = expressions.length
-    if (numArgs == 1 || numArgs == 2) {
-      ParseToTimestamp(expressions(0), expressions.drop(1).lastOption, 
TimestampNTZType)
-    } else {
-      throw QueryCompilationErrors.wrongNumArgsError(funcName, Seq(1, 2), 
numArgs)
-    }
-  }
+  override def build(funcName: String, expressions: Seq[Expression]): 
Expression =
+    ParseToTimestampBuilder.build(funcName, expressions, TimestampNTZType)
 }
 
 /**
  * Parses a column to a timestamp with local time zone based on the supplied 
format.
  */
-// scalastyle:off line.size.limit
+// scalastyle:off line.size.limit line.contains.tab
 @ExpressionDescription(
   usage = """
     _FUNC_(timestamp_str[, fmt]) - Parses the `timestamp_str` expression with 
the `fmt` expression
       to a timestamp with local time zone. Returns null with invalid input. By 
default, it follows casting rules to
       a timestamp if the `fmt` is omitted.
+
+    _FUNC_(timestamp_str, fmt, precision) - Parses the `timestamp_str` 
expression with the `fmt` expression
+      to a timestamp with local time zone with the given fractional-seconds 
precision. A precision in [7, 9] returns a
+      nanosecond-precision TIMESTAMP_LTZ(precision) and requires 
spark.sql.timestampNanosTypes.enabled to be true;
+      precision 6 returns the microsecond TIMESTAMP.
   """,
   arguments = """
     Arguments:
       * timestamp_str - A string to be parsed to timestamp with local time 
zone.
         An expression that evaluates to a string, date, timestamp, or numeric.
         If `fmt` is specified, a numeric input is cast to a string and then 
parsed with `fmt`.
+        A nanosecond-precision timestamp keeps its precision if `precision` is 
omitted.
       * fmt - Timestamp format pattern to follow. See <a 
href="https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html";>Datetime
 Patterns</a> for valid
               date and time format patterns.
         An expression that evaluates to a string.
+      * precision - An optional integer literal, either 6 or a value in [7, 
9]. Fractional digits
+        beyond `precision` are truncated.
   """,
   examples = """
     Examples:
@@ -2056,40 +2171,47 @@ object ParseToTimestampNTZExpressionBuilder extends 
ExpressionBuilder {
        2016-12-31 00:12:00
       > SELECT _FUNC_('2016-12-31', 'yyyy-MM-dd');
        2016-12-31 00:00:00
+      > SET spark.sql.timestampNanosTypes.enabled=true;
+      spark.sql.timestampNanosTypes.enabled    true
+      > SELECT _FUNC_('2016-12-31 00:12:00.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9);
+       2016-12-31 00:12:00.123456789
   """,
   group = "datetime_funcs",
   since = "3.4.0")
-// scalastyle:on line.size.limit
+// scalastyle:on line.size.limit line.contains.tab
 object ParseToTimestampLTZExpressionBuilder extends ExpressionBuilder {
-  override def build(funcName: String, expressions: Seq[Expression]): 
Expression = {
-    val numArgs = expressions.length
-    if (numArgs == 1 || numArgs == 2) {
-      ParseToTimestamp(expressions(0), expressions.drop(1).lastOption, 
TimestampType)
-    } else {
-      throw QueryCompilationErrors.wrongNumArgsError(funcName, Seq(1, 2), 
numArgs)
-    }
-  }
+  override def build(funcName: String, expressions: Seq[Expression]): 
Expression =
+    ParseToTimestampBuilder.build(funcName, expressions, TimestampType)
 }
 
 /**
  * * Parses a column to a timestamp based on the supplied format.
  */
-// scalastyle:off line.size.limit
+// scalastyle:off line.size.limit line.contains.tab
 @ExpressionDescription(
   usage = """
     _FUNC_(timestamp_str[, fmt]) - Parses the `timestamp_str` expression with 
the `fmt` expression
       to a timestamp. The function always returns null on an invalid input 
with/without ANSI SQL
       mode enabled. By default, it follows casting rules to a timestamp if the 
`fmt` is omitted.
       The result data type is consistent with the value of configuration 
`spark.sql.timestampType`.
+
+    _FUNC_(timestamp_str, fmt, precision) - Parses the `timestamp_str` 
expression with the `fmt` expression
+      to a timestamp with the given fractional-seconds precision, returning 
null on an invalid input. A precision
+      in [7, 9] returns a nanosecond-precision TIMESTAMP_LTZ(precision) or 
TIMESTAMP_NTZ(precision), following
+      `spark.sql.timestampType`, and requires 
spark.sql.timestampNanosTypes.enabled to be true; precision 6
+      returns the microsecond timestamp.
   """,
   arguments = """
     Arguments:
       * timestamp_str - A string to be parsed to timestamp.
         An expression that evaluates to a string, date, timestamp, or numeric.
         If `fmt` is specified, a numeric input is cast to a string and then 
parsed with `fmt`.
+        A nanosecond-precision timestamp keeps its precision if `precision` is 
omitted.
       * fmt - Timestamp format pattern to follow. See <a 
href="https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html";>Datetime
 Patterns</a> for valid
               date and time format patterns.
         An expression that evaluates to a string.
+      * precision - An optional integer literal, either 6 or a value in [7, 
9]. Fractional digits
+        beyond `precision` are truncated.
   """,
   examples = """
     Examples:
@@ -2099,23 +2221,60 @@ object ParseToTimestampLTZExpressionBuilder extends 
ExpressionBuilder {
        2016-12-31 00:00:00
       > SELECT _FUNC_('foo', 'yyyy-MM-dd');
        NULL
+      > SET spark.sql.timestampNanosTypes.enabled=true;
+      spark.sql.timestampNanosTypes.enabled    true
+      > SELECT _FUNC_('foo', 'yyyy-MM-dd HH:mm:ss.SSSSSSSSS', 9);
+       NULL
   """,
   group = "datetime_funcs",
   since = "3.4.0")
-// scalastyle:on line.size.limit
+// scalastyle:on line.size.limit line.contains.tab
 object TryToTimestampExpressionBuilder extends ExpressionBuilder {
-  override def build(funcName: String, expressions: Seq[Expression]): 
Expression = {
-    val numArgs = expressions.length
-    if (numArgs == 1 || numArgs == 2) {
-      ParseToTimestamp(
-        expressions.head,
-        expressions.drop(1).lastOption,
-        SQLConf.get.timestampType,
-        failOnError = false)
+  override def build(funcName: String, expressions: Seq[Expression]): 
Expression =
+    ParseToTimestampBuilder.build(
+      funcName, expressions, SQLConf.get.timestampType, failOnError = false)
+}
+
+/**
+ * Shared argument handling of the `to_timestamp`, `to_timestamp_ntz`, 
`to_timestamp_ltz` and
+ * `try_to_timestamp` builders: `(timestamp_str[, fmt[, precision]])`. 
`timestampType` is the
+ * microsecond result type of the function. An explicit `precision` (which 
requires `fmt`) selects
+ * that type (6) or its nanosecond counterpart (7-9). Without it, a nanosecond 
input keeps its
+ * precision so it is not silently narrowed, and any other input gets 
`timestampType`.
+ */
+private[expressions] object ParseToTimestampBuilder {
+  def build(
+      funcName: String,
+      expressions: Seq[Expression],
+      timestampType: DataType,
+      failOnError: Boolean = SQLConf.get.ansiEnabled): Expression = {
+    val dataType = expressions match {
+      case Seq(_) | Seq(_, _) => inputResultType(expressions.head, 
timestampType)
+      case Seq(_, _, precision) =>
+        val typeName = if (timestampType == TimestampNTZType) "TIMESTAMP_NTZ" 
else "TIMESTAMP_LTZ"
+        withPrecision(
+          timestampType,
+          CurrentTimestampPrecision.validate(funcName, precision, typeName, 
paramIndex = 3))
+      case _ =>
+        throw QueryCompilationErrors.wrongNumArgsError(funcName, Seq(1, 2, 3), 
expressions.length)
+    }
+    ParseToTimestamp(
+      expressions.head, expressions.drop(1).headOption, dataType, failOnError 
= failOnError)
+  }
+
+  private def inputResultType(left: Expression, timestampType: DataType): 
DataType = {
+    if (left.resolved && left.dataType.isInstanceOf[AnyTimestampNanoType]) {
+      withPrecision(timestampType, 
TimestampFamily.fractionalPrecision(left.dataType).get)
     } else {
-      throw QueryCompilationErrors.wrongNumArgsError(funcName, Seq(1, 2), 
numArgs)
+      timestampType
     }
   }
+
+  private def withPrecision(timestampType: DataType, precision: Int): DataType 
= precision match {
+    case 6 => timestampType
+    case p if timestampType == TimestampNTZType => TimestampNTZNanosType(p)
+    case p => TimestampLTZNanosType(p)
+  }
 }
 
 abstract class ToTimestamp
@@ -2145,7 +2304,7 @@ abstract class ToTimestamp
   override def dataType: DataType = LongType
   override def nullable: Boolean = if (failOnError) 
children.exists(_.nullable) else true
 
-  private def isParseError(e: Throwable): Boolean = e match {
+  protected def isParseError(e: Throwable): Boolean = e match {
     case _: DateTimeParseException |
          _: DateTimeException |
          _: ParseException => true
@@ -3234,22 +3393,30 @@ object TryToDateExpressionBuilder extends 
ExpressionBuilder {
 /**
  * Parses a column to a timestamp based on the supplied format.
  */
-// scalastyle:off line.size.limit
+// scalastyle:off line.size.limit line.contains.tab
 @ExpressionDescription(
   usage = """
     _FUNC_(timestamp_str[, fmt]) - Parses the `timestamp_str` expression with 
the `fmt` expression
       to a timestamp. Returns null with invalid input. By default, it follows 
casting rules to
       a timestamp if the `fmt` is omitted. The result data type is consistent 
with the value of
       configuration `spark.sql.timestampType`.
+
+    _FUNC_(timestamp_str, fmt, precision) - Parses the `timestamp_str` 
expression with the `fmt` expression
+      to a timestamp with the given fractional-seconds precision. A precision 
in [7, 9] returns a nanosecond-precision
+      TIMESTAMP_LTZ(precision) or TIMESTAMP_NTZ(precision), following 
`spark.sql.timestampType`, and requires
+      spark.sql.timestampNanosTypes.enabled to be true; precision 6 returns 
the microsecond timestamp.
   """,
   arguments = """
     Arguments:
       * timestamp_str - A string to be parsed to timestamp.
         An expression that evaluates to a string, date, timestamp, or numeric.
         If `fmt` is specified, a numeric input is cast to a string and then 
parsed with `fmt`.
+        A nanosecond-precision timestamp keeps its precision if `precision` is 
omitted.
       * fmt - Timestamp format pattern to follow. See <a 
href="https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html";>Datetime
 Patterns</a> for valid
               date and time format patterns.
         An expression that evaluates to a string.
+      * precision - An optional integer literal, either 6 or a value in [7, 
9]. Fractional digits
+        beyond `precision` are truncated.
   """,
   examples = """
     Examples:
@@ -3257,10 +3424,23 @@ object TryToDateExpressionBuilder extends 
ExpressionBuilder {
        2016-12-31 00:12:00
       > SELECT _FUNC_('2016-12-31', 'yyyy-MM-dd');
        2016-12-31 00:00:00
+      > SET spark.sql.timestampNanosTypes.enabled=true;
+      spark.sql.timestampNanosTypes.enabled    true
+      > SELECT _FUNC_('2016-12-31 00:12:00.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9);
+       2016-12-31 00:12:00.123456789
   """,
   group = "datetime_funcs",
   since = "2.2.0")
-// scalastyle:on line.size.limit
+// scalastyle:on line.size.limit line.contains.tab
+object ParseToTimestampExpressionBuilder extends ExpressionBuilder {
+  override def build(funcName: String, expressions: Seq[Expression]): 
Expression =
+    ParseToTimestampBuilder.build(funcName, expressions, 
SQLConf.get.timestampType)
+}
+
+/**
+ * Parses a column to a timestamp based on the supplied format. Without a 
format, it casts the
+ * input to `dataType`.
+ */
 case class ParseToTimestamp(
     left: Expression,
     format: Option[Expression],
@@ -3270,11 +3450,16 @@ case class ParseToTimestamp(
   extends RuntimeReplaceable with ImplicitCastInputTypes with 
TimeZoneAwareExpression {
 
   override lazy val replacement: Expression = withOrigin(origin) {
-    format.map { f =>
+    format.filterNot(_ => castsNanos).map { f =>
       GetTimestamp(left, f, dataType, "try_to_timestamp", timeZoneId, 
failOnError = failOnError)
     }.getOrElse(Cast(left, dataType, timeZoneId, ansiEnabled = failOnError))
   }
 
+  // The format only applies to a string, so a DATE or timestamp input 
converted to or from a
+  // nanosecond type is cast, as without a format.
+  private def castsNanos: Boolean = left.resolved && 
!left.dataType.isInstanceOf[StringType] &&
+    Seq(left.dataType, dataType).exists(_.isInstanceOf[AnyTimestampNanoType])
+
   def this(left: Expression, format: Expression) = {
     this(left, Option(format), SQLConf.get.timestampType)
   }
@@ -3304,8 +3489,9 @@ case class ParseToTimestamp(
     // format, `replacement` is GetTimestamp, which does not accept numeric 
inputs, so numeric
     // inputs are implicitly cast to string and parsed with the format instead.
     val acceptsNumeric = dataType.isInstanceOf[TimestampType] && format.isEmpty
+    // Nanosecond timestamps go last so they never change how the other inputs 
are coerced.
     TypeCollection(
-      (if (acceptsNumeric) types :+ NumericType else types): _*
+      (if (acceptsNumeric) types :+ NumericType else types) :+ 
AnyTimestampNanoType: _*
     ) +: format.map(_ => StringTypeWithCollation(supportsTrimCollation = 
true)).toSeq
   }
 
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/DateExpressionsSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/DateExpressionsSuite.scala
index cc0da8f1c5cf..0e7688a14673 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/DateExpressionsSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/DateExpressionsSuite.scala
@@ -28,7 +28,7 @@ import scala.language.postfixOps
 import scala.reflect.ClassTag
 import scala.util.Random
 
-import org.apache.spark.{SPARK_DOC_ROOT, SparkArithmeticException, 
SparkDateTimeException, SparkException, SparkFunSuite, 
SparkIllegalArgumentException, SparkRuntimeException, SparkUpgradeException}
+import org.apache.spark.{SPARK_DOC_ROOT, SparkArithmeticException, 
SparkDateTimeException, SparkException, SparkFunSuite, 
SparkIllegalArgumentException, SparkRuntimeException, 
SparkUnsupportedOperationException, SparkUpgradeException}
 import org.apache.spark.sql.AnalysisException
 import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
 import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.DataTypeMismatch
@@ -1283,6 +1283,84 @@ class DateExpressionsSuite extends SparkFunSuite with 
ExpressionEvalHelper {
       ToUnixTimestamp(Literal.create(null, TimestampLTZNanosType(9)), fmt, 
UTC_OPT), null)
   }
 
+  test("SPARK-57836: GetTimestamp with a nanosecond-precision result type") {
+    import org.apache.spark.sql.catalyst.util.TimestampNanosTestUtils._
+    val fmt = "yyyy-MM-dd HH:mm:ss.SSSSSSSSS"
+    val ldt = timestampNTZ(2020, 1, 1, 13, 24, 35, 123456789)
+    def ntz(e: Expression, p: Int, failOnError: Boolean): GetTimestamp =
+      GetTimestamp(e, Literal(fmt), TimestampNTZNanosType(p), timeZoneId = 
PST_OPT,
+        failOnError = failOnError)
+    def ltz(e: Expression, p: Int, failOnError: Boolean): GetTimestamp =
+      GetTimestamp(e, Literal(fmt), TimestampLTZNanosType(p), timeZoneId = 
PST_OPT,
+        failOnError = failOnError)
+
+    Seq(true, false).foreach { failOnError =>
+      foreachNanosPrecision { p =>
+        val floored = ldt.withNano(nanoOfSecTruncator(p)(ldt.getNano))
+        // Digits beyond `p` are floored. NTZ ignores the zone; LTZ parses in 
it.
+        Seq(Literal(fmt), NonFoldableLiteral(fmt)).foreach { f =>
+          checkEvaluation(
+            ntz(Literal("2020-01-01 13:24:35.123456789"), p, 
failOnError).copy(right = f),
+            localDateTimeToNanosVal(floored))
+          checkEvaluation(
+            ltz(Literal("2020-01-01 13:24:35.123456789"), p, 
failOnError).copy(right = f),
+            localDateTimeToNanosVal(floored, PST))
+        }
+        // Fewer fractional digits than `p`, and a pre-epoch value.
+        checkEvaluation(
+          ntz(Literal("2020-01-01 13:24:35.1"), p, failOnError),
+          localDateTimeToNanosVal(timestampNTZ(2020, 1, 1, 13, 24, 35, 
100000000)))
+        checkEvaluation(
+          ntz(Literal("1969-12-31 23:59:59.999999999"), p, failOnError),
+          localDateTimeToNanosVal(
+            timestampNTZ(1969, 12, 31, 23, 59, 59, 
nanoOfSecTruncator(p)(999999999))))
+
+        // Only a string is accepted; ParseToTimestamp casts other inputs.
+        Seq(
+          Literal.create(0, DateType),
+          Literal.create(0L, TimestampType),
+          Literal.create(0L, TimestampNTZType),
+          Literal.create(nanosVal(5L, 999), TimestampLTZNanosType(9))).foreach 
{ e =>
+          assert(ntz(e, p, failOnError).checkInputDataTypes().isFailure)
+          assert(ltz(e, p, failOnError).checkInputDataTypes().isFailure)
+        }
+
+        // NULL input or format.
+        checkEvaluation(ntz(Literal.create(null, StringType), p, failOnError), 
null)
+        checkEvaluation(
+          ltz(Literal("2020-01-01 13:24:35"), p, failOnError)
+            .copy(right = Literal.create(null, StringType)),
+          null)
+
+        // Invalid input fails in ANSI mode like the microsecond path, and is 
NULL otherwise.
+        Seq("Unparseable", "2020-01-01 13:24:35.1234567891").foreach { s =>
+          Seq(ntz(Literal(s), p, failOnError), ltz(Literal(s), p, 
failOnError)).foreach { e =>
+            if (failOnError) {
+              checkExceptionInExpression[SparkDateTimeException](e, "could not 
be parsed")
+            } else {
+              checkEvaluation(e, null)
+            }
+          }
+        }
+      }
+    }
+
+    // The LEGACY parser can't parse nanoseconds: LTZ raises a clean error 
even when
+    // failOnError is false. NTZ always uses the non-legacy parser.
+    withSQLConf(SQLConf.LEGACY_TIME_PARSER_POLICY.key -> "LEGACY") {
+      Seq(true, false).foreach { failOnError =>
+        Seq(Literal(fmt), NonFoldableLiteral(fmt)).foreach { f =>
+          checkExceptionInExpression[SparkUnsupportedOperationException](
+            ltz(Literal("2020-01-01 13:24:35.123456789"), 9, 
failOnError).copy(right = f),
+            "LEGACY time parser policy")
+          checkEvaluation(
+            ntz(Literal("2020-01-01 13:24:35.123456789"), 9, 
failOnError).copy(right = f),
+            localDateTimeToNanosVal(ldt))
+        }
+      }
+    }
+  }
+
   test("datediff") {
     checkEvaluation(
       DateDiff(Literal(Date.valueOf("2015-07-24")), 
Literal(Date.valueOf("2015-07-21"))), 3)
@@ -3929,8 +4007,9 @@ class DateExpressionsSuite extends SparkFunSuite with 
ExpressionEvalHelper {
     assert(CurrentTimestampExpressionBuilder.build("current_timestamp", 
Seq(Add(Literal(4),
       Literal(5)))) === CurrentTimestampNanos(9))
 
-    // Out-of-range precision (other than 6) is rejected with 
INVALID_TIMESTAMP_PRECISION.
-    Seq(0, 3, 5, 10).foreach { p =>
+    // Out-of-range precision (other than 6) is rejected with 
INVALID_TIMESTAMP_PRECISION. A
+    // BIGINT precision does not wrap into range.
+    Seq[Any](0, 3, 5, 10, 4294967305L).foreach { p =>
       checkError(
         exception = intercept[SparkException] {
           CurrentTimestampExpressionBuilder.build("current_timestamp", 
Seq(Literal(p)))
diff --git a/sql/core/src/test/resources/sql-functions/sql-expression-schema.md 
b/sql/core/src/test/resources/sql-functions/sql-expression-schema.md
index 0499fa05a029..86a22d3f61e2 100644
--- a/sql/core/src/test/resources/sql-functions/sql-expression-schema.md
+++ b/sql/core/src/test/resources/sql-functions/sql-expression-schema.md
@@ -286,7 +286,7 @@
 | org.apache.spark.sql.catalyst.expressions.Overlay | overlay | SELECT 
overlay('Spark SQL' PLACING '_' FROM 6) | struct<overlay(Spark SQL, _, 6, 
-1):string> |
 | org.apache.spark.sql.catalyst.expressions.ParseSql | parse_sql | SELECT 
parse_sql('SELECT 1;SELECT 2') | struct<parse_sql(SELECT 1;SELECT 2):string> |
 | org.apache.spark.sql.catalyst.expressions.ParseToDate | to_date | SELECT 
to_date('2009-07-30 04:17:52') | struct<to_date(2009-07-30 04:17:52):date> |
-| org.apache.spark.sql.catalyst.expressions.ParseToTimestamp | to_timestamp | 
SELECT to_timestamp('2016-12-31 00:12:00') | struct<to_timestamp(2016-12-31 
00:12:00):timestamp> |
+| org.apache.spark.sql.catalyst.expressions.ParseToTimestampExpressionBuilder 
| to_timestamp | SELECT to_timestamp('2016-12-31 00:12:00') | 
struct<to_timestamp(2016-12-31 00:12:00):timestamp> |
 | 
org.apache.spark.sql.catalyst.expressions.ParseToTimestampLTZExpressionBuilder 
| to_timestamp_ltz | SELECT to_timestamp_ltz('2016-12-31 00:12:00') | 
struct<to_timestamp_ltz(2016-12-31 00:12:00):timestamp> |
 | 
org.apache.spark.sql.catalyst.expressions.ParseToTimestampNTZExpressionBuilder 
| to_timestamp_ntz | SELECT to_timestamp_ntz('2016-12-31 00:12:00') | 
struct<to_timestamp_ntz(2016-12-31 00:12:00):timestamp_ntz> |
 | org.apache.spark.sql.catalyst.expressions.ParseUrl | parse_url | SELECT 
parse_url('http://spark.apache.org/path?query=1', 'HOST') | 
struct<parse_url(http://spark.apache.org/path?query=1, HOST):string> |
diff --git 
a/sql/core/src/test/resources/sql-tests/analyzer-results/timestamp-ltz-nanos.sql.out
 
b/sql/core/src/test/resources/sql-tests/analyzer-results/timestamp-ltz-nanos.sql.out
index e72dbc89fb57..6bbd4ff1ee0a 100644
--- 
a/sql/core/src/test/resources/sql-tests/analyzer-results/timestamp-ltz-nanos.sql.out
+++ 
b/sql/core/src/test/resources/sql-tests/analyzer-results/timestamp-ltz-nanos.sql.out
@@ -1732,6 +1732,121 @@ SELECT timestampadd(NANOSECOND, 1, TIMESTAMP_LTZ 
'2020-01-01 00:00:00 UTC')
 [Analyzer test output redacted due to nondeterminism]
 
 
+-- !query
+SELECT to_timestamp('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)
+-- !query analysis
+Project [to_timestamp(2020-01-01 13:24:35.123456789, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampLTZNanosType(9), Some(America/Los_Angeles), true) 
AS to_timestamp(2020-01-01 13:24:35.123456789, yyyy-MM-dd HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ltz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 7)
+-- !query analysis
+Project [to_timestamp_ltz(2020-01-01 13:24:35.123456789, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampLTZNanosType(7), Some(America/Los_Angeles), true) 
AS to_timestamp_ltz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT try_to_timestamp('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8)
+-- !query analysis
+Project [try_to_timestamp(2020-01-01 13:24:35.123456789, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampLTZNanosType(8), Some(America/Los_Angeles), 
false) AS try_to_timestamp(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT typeof(to_timestamp('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)),
+  typeof(to_timestamp_ltz('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 6))
+-- !query analysis
+Project [typeof(to_timestamp(2020-01-01 13:24:35.1, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampLTZNanosType(9), Some(America/Los_Angeles), 
true)) AS typeof(to_timestamp(2020-01-01 13:24:35.1, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS))#x, typeof(to_timestamp_ltz(2020-01-01 13:24:35.1, 
Some(yyyy-MM-dd HH:mm:ss.SSSSSSSSS), TimestampType, Some(America/Los_Angeles), 
true)) AS typeof(to_timestamp_ltz(2020-01-01 13:24:35.1, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS))#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp('2020-01-01 13:24:35.123456789 UTC', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z', 9)
+-- !query analysis
+Project [to_timestamp(2020-01-01 13:24:35.123456789 UTC, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z), TimestampLTZNanosType(9), Some(America/Los_Angeles), 
true) AS to_timestamp(2020-01-01 13:24:35.123456789 UTC, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT try_to_timestamp('bad', 'yyyy', 9)
+-- !query analysis
+Project [try_to_timestamp(bad, Some(yyyy), TimestampLTZNanosType(9), 
Some(America/Los_Angeles), false) AS try_to_timestamp(bad, yyyy)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp('bad', 'yyyy', 9)
+-- !query analysis
+Project [to_timestamp(bad, Some(yyyy), TimestampLTZNanosType(9), 
Some(America/Los_Angeles), true) AS to_timestamp(bad, yyyy)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'))
+-- !query analysis
+Project [to_timestamp_ltz(2020-01-01 13:24:35.123456789, None, 
TimestampLTZNanosType(9), Some(America/Los_Angeles), true) AS 
to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789')#x, 
typeof(to_timestamp_ltz(2020-01-01 13:24:35.123456789, None, 
TimestampLTZNanosType(9), Some(America/Los_Angeles), true)) AS 
typeof(to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'))#x]
++- OneRowRelation
+
+
+-- !query
+SELECT try_to_timestamp('2020-01-01 13:24:35.12345678' :: timestamp_ltz(8), 
'yyyy'),
+  typeof(try_to_timestamp('2020-01-01 13:24:35.12345678' :: timestamp_ltz(8), 
'yyyy'))
+-- !query analysis
+Project [try_to_timestamp(cast(2020-01-01 13:24:35.12345678 as 
timestamp_ltz(8)), Some(yyyy), TimestampLTZNanosType(8), 
Some(America/Los_Angeles), false) AS try_to_timestamp(CAST(2020-01-01 
13:24:35.12345678 AS TIMESTAMP_LTZ(8)), yyyy)#x, 
typeof(try_to_timestamp(cast(2020-01-01 13:24:35.12345678 as timestamp_ltz(8)), 
Some(yyyy), TimestampLTZNanosType(8), Some(America/Los_Angeles), false)) AS 
typeof(try_to_timestamp(CAST(2020-01-01 13:24:35.12345678 AS TIMESTAMP_LTZ(8)), 
yyyy))#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', 'yyyy', 7)
+-- !query analysis
+Project [to_timestamp(2020-01-01 13:24:35.123456789, Some(yyyy), 
TimestampLTZNanosType(7), Some(America/Los_Angeles), true) AS 
to_timestamp(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', yyyy)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'))
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789, None, 
TimestampNTZNanosType(9), Some(America/Los_Angeles), true) AS 
to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789')#x, 
typeof(to_timestamp_ntz(2020-01-01 13:24:35.123456789, None, 
TimestampNTZNanosType(9), Some(America/Los_Angeles), true)) AS 
typeof(to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'))#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp('2020', 'yyyy', 5)
+-- !query analysis
+org.apache.spark.SparkException
+{
+  "errorClass" : "INVALID_TIMESTAMP_PRECISION",
+  "sqlState" : "22023",
+  "messageParameters" : {
+    "precision" : "5",
+    "type" : "TIMESTAMP_LTZ"
+  }
+}
+
+
+-- !query
+SELECT to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', 'yyyy', 
9)
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789, Some(yyyy), 
TimestampNTZNanosType(9), Some(America/Los_Angeles), true) AS 
to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', yyyy)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456', 'yyyy', 9)
+-- !query analysis
+Project [to_timestamp(2020-01-01 13:24:35.123456, Some(yyyy), 
TimestampLTZNanosType(9), Some(America/Los_Angeles), true) AS 
to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456', yyyy)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ltz(DATE '2020-01-01', 'yyyy-MM-dd', 9)
+-- !query analysis
+[Analyzer test output redacted due to nondeterminism]
+
+
 -- !query
 SELECT timestampdiff(MICROSECOND, TIMESTAMP_LTZ '2020-01-01 
00:00:00.000000999',
     TIMESTAMP_LTZ '2020-01-01 00:00:00.000001001')
diff --git 
a/sql/core/src/test/resources/sql-tests/analyzer-results/timestamp-ntz-nanos.sql.out
 
b/sql/core/src/test/resources/sql-tests/analyzer-results/timestamp-ntz-nanos.sql.out
index fbd770fea6f6..2b14e2b8a653 100644
--- 
a/sql/core/src/test/resources/sql-tests/analyzer-results/timestamp-ntz-nanos.sql.out
+++ 
b/sql/core/src/test/resources/sql-tests/analyzer-results/timestamp-ntz-nanos.sql.out
@@ -1701,6 +1701,143 @@ Project [timestampadd(NANOSECOND, cast(50 as bigint), 
cast(2020-01-01 00:00:00.0
 +- OneRowRelation
 
 
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampNTZNanosType(9), Some(America/Los_Angeles), true) 
AS to_timestamp_ntz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8)
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampNTZNanosType(8), Some(America/Los_Angeles), true) 
AS to_timestamp_ntz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 7)
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampNTZNanosType(7), Some(America/Los_Angeles), true) 
AS to_timestamp_ntz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 6)
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampNTZType, Some(America/Los_Angeles), true) AS 
to_timestamp_ntz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz('1969-12-31 23:59:59.999999999', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)
+-- !query analysis
+Project [to_timestamp_ntz(1969-12-31 23:59:59.999999999, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampNTZNanosType(9), Some(America/Los_Angeles), true) 
AS to_timestamp_ntz(1969-12-31 23:59:59.999999999, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789 UTC', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z', 9)
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789 UTC, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z), TimestampNTZNanosType(9), Some(America/Los_Angeles), 
true) AS to_timestamp_ntz(2020-01-01 13:24:35.123456789 UTC, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT typeof(to_timestamp_ntz('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8))
+-- !query analysis
+Project [typeof(to_timestamp_ntz(2020-01-01 13:24:35.1, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampNTZNanosType(8), Some(America/Los_Angeles), 
true)) AS typeof(to_timestamp_ntz(2020-01-01 13:24:35.1, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS))#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz('bad', 'yyyy-MM-dd', 9)
+-- !query analysis
+Project [to_timestamp_ntz(bad, Some(yyyy-MM-dd), TimestampNTZNanosType(9), 
Some(America/Los_Angeles), true) AS to_timestamp_ntz(bad, yyyy-MM-dd)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'))
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789, None, 
TimestampNTZNanosType(9), Some(America/Los_Angeles), true) AS 
to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789')#x, 
typeof(to_timestamp_ntz(2020-01-01 13:24:35.123456789, None, 
TimestampNTZNanosType(9), Some(America/Los_Angeles), true)) AS 
typeof(to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'))#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.12345678' :: timestamp_ntz(8), 
'yyyy'),
+  typeof(to_timestamp_ntz('2020-01-01 13:24:35.12345678' :: timestamp_ntz(8), 
'yyyy'))
+-- !query analysis
+Project [to_timestamp_ntz(cast(2020-01-01 13:24:35.12345678 as 
timestamp_ntz(8)), Some(yyyy), TimestampNTZNanosType(8), 
Some(America/Los_Angeles), true) AS to_timestamp_ntz(CAST(2020-01-01 
13:24:35.12345678 AS TIMESTAMP_NTZ(8)), yyyy)#x, 
typeof(to_timestamp_ntz(cast(2020-01-01 13:24:35.12345678 as timestamp_ntz(8)), 
Some(yyyy), TimestampNTZNanosType(8), Some(America/Los_Angeles), true)) AS 
typeof(to_timestamp_ntz(CAST(2020-01-01 13:24:35.12345678 AS TIMESTAMP_NTZ(8)), 
yyyy))#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', 'yyyy', 
7)
+-- !query analysis
+Project [to_timestamp_ntz(2020-01-01 13:24:35.123456789, Some(yyyy), 
TimestampNTZNanosType(7), Some(America/Los_Angeles), true) AS 
to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', yyyy)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'))
+-- !query analysis
+Project [to_timestamp(2020-01-01 13:24:35.123456789, None, 
TimestampLTZNanosType(9), Some(America/Los_Angeles), true) AS 
to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789')#x, 
typeof(to_timestamp(2020-01-01 13:24:35.123456789, None, 
TimestampLTZNanosType(9), Some(America/Los_Angeles), true)) AS 
typeof(to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'))#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35', 'yyyy-MM-dd HH:mm:ss', 10)
+-- !query analysis
+org.apache.spark.SparkException
+{
+  "errorClass" : "INVALID_TIMESTAMP_PRECISION",
+  "sqlState" : "22023",
+  "messageParameters" : {
+    "precision" : "10",
+    "type" : "TIMESTAMP_NTZ"
+  }
+}
+
+
+-- !query
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS')
+-- !query analysis
+Project [to_timestamp(2020-01-01 13:24:35.123456789, Some(yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS), TimestampLTZNanosType(9), Some(America/Los_Angeles), true) 
AS to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)#x]
++- OneRowRelation
+
+
+-- !query
+SELECT to_timestamp_ntz(DATE '2020-01-01', 'yyyy-MM-dd', 9)
+-- !query analysis
+[Analyzer test output redacted due to nondeterminism]
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35', 'yyyy-MM-dd HH:mm:ss', 9, 9)
+-- !query analysis
+org.apache.spark.sql.AnalysisException
+{
+  "errorClass" : "WRONG_NUM_ARGS.WITHOUT_SUGGESTION",
+  "sqlState" : "42605",
+  "messageParameters" : {
+    "actualNum" : "4",
+    "docroot" : "https://spark.apache.org/docs/latest";,
+    "expectedNum" : "[1, 2, 3]",
+    "functionName" : "`to_timestamp_ntz`"
+  },
+  "queryContext" : [ {
+    "objectType" : "",
+    "objectName" : "",
+    "startIndex" : 8,
+    "stopIndex" : 75,
+    "fragment" : "to_timestamp_ntz('2020-01-01 13:24:35', 'yyyy-MM-dd 
HH:mm:ss', 9, 9)"
+  } ]
+}
+
+
 -- !query
 SELECT timestampdiff(MICROSECOND, TIMESTAMP_NTZ '2020-01-01 
00:00:00.000000999',
     TIMESTAMP_NTZ '2020-01-01 00:00:00.000001001')
diff --git 
a/sql/core/src/test/resources/sql-tests/inputs/timestamp-ltz-nanos.sql 
b/sql/core/src/test/resources/sql-tests/inputs/timestamp-ltz-nanos.sql
index 44ac3ba021af..f46528745b86 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/timestamp-ltz-nanos.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/timestamp-ltz-nanos.sql
@@ -603,6 +603,31 @@ SELECT timestampadd(NANOSECOND, 900, TIMESTAMP_LTZ 
'2020-01-01 00:00:00.00000020
 -- NANOSECOND is rejected on a microsecond-precision timestamp (nanoseconds 
are unrepresentable).
 SELECT timestampadd(NANOSECOND, 1, TIMESTAMP_LTZ '2020-01-01 00:00:00 UTC');
 
+-- SPARK-57836: to_timestamp / to_timestamp_ltz / try_to_timestamp(str, fmt, 
p) parse up to 9
+-- fractional digits into TIMESTAMP_LTZ(p), flooring the digits beyond p; p = 
6 keeps TIMESTAMP.
+-- A TIMESTAMP_LTZ(p) input keeps p.
+SELECT to_timestamp('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9);
+SELECT to_timestamp_ltz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 7);
+SELECT try_to_timestamp('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8);
+SELECT typeof(to_timestamp('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)),
+  typeof(to_timestamp_ltz('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 6));
+SELECT to_timestamp('2020-01-01 13:24:35.123456789 UTC', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z', 9);
+SELECT try_to_timestamp('bad', 'yyyy', 9);
+SELECT to_timestamp('bad', 'yyyy', 9);
+SELECT to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'));
+SELECT try_to_timestamp('2020-01-01 13:24:35.12345678' :: timestamp_ltz(8), 
'yyyy'),
+  typeof(try_to_timestamp('2020-01-01 13:24:35.12345678' :: timestamp_ltz(8), 
'yyyy'));
+SELECT to_timestamp(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', 'yyyy', 7);
+SELECT to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'));
+SELECT to_timestamp('2020', 'yyyy', 5);
+-- With a nanosecond input or result, a DATE or timestamp input ignores the 
format and
+-- converts like CAST.
+SELECT to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', 'yyyy', 
9);
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456', 'yyyy', 9);
+SELECT to_timestamp_ltz(DATE '2020-01-01', 'yyyy-MM-dd', 9);
+
 -- Functions without TIMESTAMP_LTZ(p) support reject it in both ANSI modes 
instead of implicitly
 -- narrowing it to a microsecond timestamp, DATE or TIME. Date-valued 
functions still take it
 -- as DATE.
diff --git 
a/sql/core/src/test/resources/sql-tests/inputs/timestamp-ntz-nanos.sql 
b/sql/core/src/test/resources/sql-tests/inputs/timestamp-ntz-nanos.sql
index 4f3b03e50103..3e5c2143d6a1 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/timestamp-ntz-nanos.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/timestamp-ntz-nanos.sql
@@ -596,6 +596,30 @@ SELECT timestampadd(NANOSECOND, 1, TIMESTAMP_NTZ 
'2020-01-01 00:00:00');
 SELECT timestampadd(NANOSECOND, 150, '2020-01-01 00:00:00.0000001' :: 
timestamp_ntz(7));
 SELECT timestampadd(NANOSECOND, 50, '2020-01-01 00:00:00.0000001' :: 
timestamp_ntz(7));
 
+-- SPARK-57836: to_timestamp_ntz(str, fmt, p) parses up to 9 fractional digits 
into TIMESTAMP_NTZ(p),
+-- flooring the digits beyond p; p = 6 keeps TIMESTAMP_NTZ. A TIMESTAMP_NTZ(p) 
input keeps p.
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9);
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8);
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 7);
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 6);
+SELECT to_timestamp_ntz('1969-12-31 23:59:59.999999999', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9);
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789 UTC', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z', 9);
+SELECT typeof(to_timestamp_ntz('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8));
+SELECT to_timestamp_ntz('bad', 'yyyy-MM-dd', 9);
+SELECT to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'));
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.12345678' :: timestamp_ntz(8), 
'yyyy'),
+  typeof(to_timestamp_ntz('2020-01-01 13:24:35.12345678' :: timestamp_ntz(8), 
'yyyy'));
+SELECT to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', 'yyyy', 
7);
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'));
+SELECT to_timestamp_ntz('2020-01-01 13:24:35', 'yyyy-MM-dd HH:mm:ss', 10);
+-- With a nanosecond input or result, a DATE or timestamp input ignores the 
format and
+-- converts like CAST.
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS');
+SELECT to_timestamp_ntz(DATE '2020-01-01', 'yyyy-MM-dd', 9);
+SELECT to_timestamp_ntz('2020-01-01 13:24:35', 'yyyy-MM-dd HH:mm:ss', 9, 9);
+
 -- Functions without TIMESTAMP_NTZ(p) support reject it in both ANSI modes 
instead of implicitly
 -- narrowing it to a microsecond timestamp, DATE or TIME. Date-valued 
functions still take it
 -- as DATE.
diff --git 
a/sql/core/src/test/resources/sql-tests/results/timestamp-ltz-nanos.sql.out 
b/sql/core/src/test/resources/sql-tests/results/timestamp-ltz-nanos.sql.out
index 7cc84025007f..148b9938e99c 100644
--- a/sql/core/src/test/resources/sql-tests/results/timestamp-ltz-nanos.sql.out
+++ b/sql/core/src/test/resources/sql-tests/results/timestamp-ltz-nanos.sql.out
@@ -1871,6 +1871,146 @@ org.apache.spark.SparkIllegalArgumentException
 }
 
 
+-- !query
+SELECT to_timestamp('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)
+-- !query schema
+struct<to_timestamp(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ltz(9)>
+-- !query output
+2020-01-01 13:24:35.123456789
+
+
+-- !query
+SELECT to_timestamp_ltz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 7)
+-- !query schema
+struct<to_timestamp_ltz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ltz(7)>
+-- !query output
+2020-01-01 13:24:35.1234567
+
+
+-- !query
+SELECT try_to_timestamp('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8)
+-- !query schema
+struct<try_to_timestamp(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ltz(8)>
+-- !query output
+2020-01-01 13:24:35.12345678
+
+
+-- !query
+SELECT typeof(to_timestamp('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)),
+  typeof(to_timestamp_ltz('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 6))
+-- !query schema
+struct<typeof(to_timestamp(2020-01-01 13:24:35.1, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)):string,typeof(to_timestamp_ltz(2020-01-01 13:24:35.1, 
yyyy-MM-dd HH:mm:ss.SSSSSSSSS)):string>
+-- !query output
+timestamp_ltz(9)       timestamp
+
+
+-- !query
+SELECT to_timestamp('2020-01-01 13:24:35.123456789 UTC', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z', 9)
+-- !query schema
+struct<to_timestamp(2020-01-01 13:24:35.123456789 UTC, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z):timestamp_ltz(9)>
+-- !query output
+2020-01-01 05:24:35.123456789
+
+
+-- !query
+SELECT try_to_timestamp('bad', 'yyyy', 9)
+-- !query schema
+struct<try_to_timestamp(bad, yyyy):timestamp_ltz(9)>
+-- !query output
+NULL
+
+
+-- !query
+SELECT to_timestamp('bad', 'yyyy', 9)
+-- !query schema
+struct<>
+-- !query output
+org.apache.spark.SparkDateTimeException
+{
+  "errorClass" : "CANNOT_PARSE_TIMESTAMP",
+  "sqlState" : "22007",
+  "messageParameters" : {
+    "func" : "`try_to_timestamp`",
+    "message" : "Text 'bad' could not be parsed at index 0"
+  }
+}
+
+
+-- !query
+SELECT to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'))
+-- !query schema
+struct<to_timestamp_ltz(TIMESTAMP_LTZ '2020-01-01 
13:24:35.123456789'):timestamp_ltz(9),typeof(to_timestamp_ltz(TIMESTAMP_LTZ 
'2020-01-01 13:24:35.123456789')):string>
+-- !query output
+2020-01-01 13:24:35.123456789  timestamp_ltz(9)
+
+
+-- !query
+SELECT try_to_timestamp('2020-01-01 13:24:35.12345678' :: timestamp_ltz(8), 
'yyyy'),
+  typeof(try_to_timestamp('2020-01-01 13:24:35.12345678' :: timestamp_ltz(8), 
'yyyy'))
+-- !query schema
+struct<try_to_timestamp(CAST(2020-01-01 13:24:35.12345678 AS 
TIMESTAMP_LTZ(8)), 
yyyy):timestamp_ltz(8),typeof(try_to_timestamp(CAST(2020-01-01 
13:24:35.12345678 AS TIMESTAMP_LTZ(8)), yyyy)):string>
+-- !query output
+2020-01-01 13:24:35.12345678   timestamp_ltz(8)
+
+
+-- !query
+SELECT to_timestamp(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', 'yyyy', 7)
+-- !query schema
+struct<to_timestamp(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', 
yyyy):timestamp_ltz(7)>
+-- !query output
+2020-01-01 13:24:35.1234567
+
+
+-- !query
+SELECT to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789'))
+-- !query schema
+struct<to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 
13:24:35.123456789'):timestamp_ntz(9),typeof(to_timestamp_ntz(TIMESTAMP_LTZ 
'2020-01-01 13:24:35.123456789')):string>
+-- !query output
+2020-01-01 13:24:35.123456789  timestamp_ntz(9)
+
+
+-- !query
+SELECT to_timestamp('2020', 'yyyy', 5)
+-- !query schema
+struct<>
+-- !query output
+org.apache.spark.SparkException
+{
+  "errorClass" : "INVALID_TIMESTAMP_PRECISION",
+  "sqlState" : "22023",
+  "messageParameters" : {
+    "precision" : "5",
+    "type" : "TIMESTAMP_LTZ"
+  }
+}
+
+
+-- !query
+SELECT to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', 'yyyy', 
9)
+-- !query schema
+struct<to_timestamp_ntz(TIMESTAMP_LTZ '2020-01-01 13:24:35.123456789', 
yyyy):timestamp_ntz(9)>
+-- !query output
+2020-01-01 13:24:35.123456789
+
+
+-- !query
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456', 'yyyy', 9)
+-- !query schema
+struct<to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456', 
yyyy):timestamp_ltz(9)>
+-- !query output
+2020-01-01 13:24:35.123456
+
+
+-- !query
+SELECT to_timestamp_ltz(DATE '2020-01-01', 'yyyy-MM-dd', 9)
+-- !query schema
+struct<to_timestamp_ltz(DATE '2020-01-01', yyyy-MM-dd):timestamp_ltz(9)>
+-- !query output
+2020-01-01 00:00:00
+
+
 -- !query
 SELECT timestampdiff(MICROSECOND, TIMESTAMP_LTZ '2020-01-01 
00:00:00.000000999',
     TIMESTAMP_LTZ '2020-01-01 00:00:00.000001001')
diff --git 
a/sql/core/src/test/resources/sql-tests/results/timestamp-ntz-nanos.sql.out 
b/sql/core/src/test/resources/sql-tests/results/timestamp-ntz-nanos.sql.out
index b40f4f3a0107..b575aa965d67 100644
--- a/sql/core/src/test/resources/sql-tests/results/timestamp-ntz-nanos.sql.out
+++ b/sql/core/src/test/resources/sql-tests/results/timestamp-ntz-nanos.sql.out
@@ -1761,6 +1761,170 @@ struct<timestampadd(NANOSECOND, 50, CAST(2020-01-01 
00:00:00.0000001 AS TIMESTAM
 2020-01-01 00:00:00.0000001
 
 
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)
+-- !query schema
+struct<to_timestamp_ntz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ntz(9)>
+-- !query output
+2020-01-01 13:24:35.123456789
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8)
+-- !query schema
+struct<to_timestamp_ntz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ntz(8)>
+-- !query output
+2020-01-01 13:24:35.12345678
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 7)
+-- !query schema
+struct<to_timestamp_ntz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ntz(7)>
+-- !query output
+2020-01-01 13:24:35.1234567
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 6)
+-- !query schema
+struct<to_timestamp_ntz(2020-01-01 13:24:35.123456789, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ntz>
+-- !query output
+2020-01-01 13:24:35.123456
+
+
+-- !query
+SELECT to_timestamp_ntz('1969-12-31 23:59:59.999999999', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 9)
+-- !query schema
+struct<to_timestamp_ntz(1969-12-31 23:59:59.999999999, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ntz(9)>
+-- !query output
+1969-12-31 23:59:59.999999999
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.123456789 UTC', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z', 9)
+-- !query schema
+struct<to_timestamp_ntz(2020-01-01 13:24:35.123456789 UTC, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS z):timestamp_ntz(9)>
+-- !query output
+2020-01-01 13:24:35.123456789
+
+
+-- !query
+SELECT typeof(to_timestamp_ntz('2020-01-01 13:24:35.1', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS', 8))
+-- !query schema
+struct<typeof(to_timestamp_ntz(2020-01-01 13:24:35.1, yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS)):string>
+-- !query output
+timestamp_ntz(8)
+
+
+-- !query
+SELECT to_timestamp_ntz('bad', 'yyyy-MM-dd', 9)
+-- !query schema
+struct<>
+-- !query output
+org.apache.spark.SparkDateTimeException
+{
+  "errorClass" : "CANNOT_PARSE_TIMESTAMP",
+  "sqlState" : "22007",
+  "messageParameters" : {
+    "func" : "`try_to_timestamp`",
+    "message" : "Text 'bad' could not be parsed at index 0"
+  }
+}
+
+
+-- !query
+SELECT to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'))
+-- !query schema
+struct<to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 
13:24:35.123456789'):timestamp_ntz(9),typeof(to_timestamp_ntz(TIMESTAMP_NTZ 
'2020-01-01 13:24:35.123456789')):string>
+-- !query output
+2020-01-01 13:24:35.123456789  timestamp_ntz(9)
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35.12345678' :: timestamp_ntz(8), 
'yyyy'),
+  typeof(to_timestamp_ntz('2020-01-01 13:24:35.12345678' :: timestamp_ntz(8), 
'yyyy'))
+-- !query schema
+struct<to_timestamp_ntz(CAST(2020-01-01 13:24:35.12345678 AS 
TIMESTAMP_NTZ(8)), 
yyyy):timestamp_ntz(8),typeof(to_timestamp_ntz(CAST(2020-01-01 
13:24:35.12345678 AS TIMESTAMP_NTZ(8)), yyyy)):string>
+-- !query output
+2020-01-01 13:24:35.12345678   timestamp_ntz(8)
+
+
+-- !query
+SELECT to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', 'yyyy', 
7)
+-- !query schema
+struct<to_timestamp_ntz(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', 
yyyy):timestamp_ntz(7)>
+-- !query output
+2020-01-01 13:24:35.1234567
+
+
+-- !query
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'),
+  typeof(to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789'))
+-- !query schema
+struct<to_timestamp(TIMESTAMP_NTZ '2020-01-01 
13:24:35.123456789'):timestamp_ltz(9),typeof(to_timestamp(TIMESTAMP_NTZ 
'2020-01-01 13:24:35.123456789')):string>
+-- !query output
+2020-01-01 13:24:35.123456789  timestamp_ltz(9)
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35', 'yyyy-MM-dd HH:mm:ss', 10)
+-- !query schema
+struct<>
+-- !query output
+org.apache.spark.SparkException
+{
+  "errorClass" : "INVALID_TIMESTAMP_PRECISION",
+  "sqlState" : "22023",
+  "messageParameters" : {
+    "precision" : "10",
+    "type" : "TIMESTAMP_NTZ"
+  }
+}
+
+
+-- !query
+SELECT to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', 'yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS')
+-- !query schema
+struct<to_timestamp(TIMESTAMP_NTZ '2020-01-01 13:24:35.123456789', yyyy-MM-dd 
HH:mm:ss.SSSSSSSSS):timestamp_ltz(9)>
+-- !query output
+2020-01-01 13:24:35.123456789
+
+
+-- !query
+SELECT to_timestamp_ntz(DATE '2020-01-01', 'yyyy-MM-dd', 9)
+-- !query schema
+struct<to_timestamp_ntz(DATE '2020-01-01', yyyy-MM-dd):timestamp_ntz(9)>
+-- !query output
+2020-01-01 00:00:00
+
+
+-- !query
+SELECT to_timestamp_ntz('2020-01-01 13:24:35', 'yyyy-MM-dd HH:mm:ss', 9, 9)
+-- !query schema
+struct<>
+-- !query output
+org.apache.spark.sql.AnalysisException
+{
+  "errorClass" : "WRONG_NUM_ARGS.WITHOUT_SUGGESTION",
+  "sqlState" : "42605",
+  "messageParameters" : {
+    "actualNum" : "4",
+    "docroot" : "https://spark.apache.org/docs/latest";,
+    "expectedNum" : "[1, 2, 3]",
+    "functionName" : "`to_timestamp_ntz`"
+  },
+  "queryContext" : [ {
+    "objectType" : "",
+    "objectName" : "",
+    "startIndex" : 8,
+    "stopIndex" : 75,
+    "fragment" : "to_timestamp_ntz('2020-01-01 13:24:35', 'yyyy-MM-dd 
HH:mm:ss', 9, 9)"
+  } ]
+}
+
+
 -- !query
 SELECT timestampdiff(MICROSECOND, TIMESTAMP_NTZ '2020-01-01 
00:00:00.000000999',
     TIMESTAMP_NTZ '2020-01-01 00:00:00.000001001')
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/TimestampNanosFunctionsSuiteBase.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/TimestampNanosFunctionsSuiteBase.scala
index 8de2e73c8dd8..bf3e19f7a604 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/TimestampNanosFunctionsSuiteBase.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/TimestampNanosFunctionsSuiteBase.scala
@@ -17,9 +17,11 @@
 
 package org.apache.spark.sql
 
+import java.sql.Timestamp
 import java.time.{Instant, LocalDateTime, LocalTime}
 
-import org.apache.spark.{SparkConf, SparkException, SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.{SPARK_DOC_ROOT, SparkConf, SparkDateTimeException, 
SparkException, SparkRuntimeException, SparkUnsupportedOperationException}
+import 
org.apache.spark.sql.catalyst.util.TimestampNanosTestUtils.nanoOfSecTruncator
 import org.apache.spark.sql.functions._
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.test.SharedSparkSession
@@ -1047,6 +1049,194 @@ abstract class TimestampNanosFunctionsSuiteBase extends 
SharedSparkSession {
         LocalDateTime.parse("2020-01-01T00:00:01.000000900"))))
   }
 
+  private val toTimestampFns =
+    Seq("to_timestamp", "to_timestamp_ltz", "to_timestamp_ntz", 
"try_to_timestamp")
+
+  test("SPARK-57836: to_timestamp* with a precision parse nanosecond-precision 
timestamps") {
+    import testImplicits._
+    val fmt = "yyyy-MM-dd HH:mm:ss.SSSSSSSSS"
+    val df = Seq("2020-01-01 13:24:35.123456789", null).toDF("s")
+    Seq(7, 8, 9).foreach { p =>
+      val sqlRes = df.selectExpr(toTimestampFns.map(fn => s"$fn(s, '$fmt', 
$p)"): _*)
+      val colRes =
+        df.select(toTimestampFns.map(call_function(_, col("s"), lit(fmt), 
lit(p))): _*)
+      checkAnswer(sqlRes, colRes)
+      assert(sqlRes.schema.map(_.dataType) === Seq(
+        TimestampLTZNanosType(p), TimestampLTZNanosType(p),
+        TimestampNTZNanosType(p), TimestampLTZNanosType(p)))
+      // Digits beyond `p` are floored. LTZ parses in the session time zone 
(UTC-8 in January).
+      val nanos = nanoOfSecTruncator(p)(123456789)
+      val ltz = Instant.parse("2020-01-01T21:24:35Z").plusNanos(nanos)
+      val ntz = LocalDateTime.parse("2020-01-01T13:24:35").plusNanos(nanos)
+      checkAnswer(sqlRes, Seq(Row(ltz, ltz, ntz, ltz), Row(null, null, null, 
null)))
+    }
+    // Precision 6 keeps the microsecond types.
+    assert(df.selectExpr(toTimestampFns.map(fn => s"$fn(s, '$fmt', 6)"): 
_*).schema
+      .map(_.dataType) === Seq(TimestampType, TimestampType, TimestampNTZType, 
TimestampType))
+    // to_timestamp and try_to_timestamp follow spark.sql.timestampType.
+    withSQLConf(SQLConf.TIMESTAMP_TYPE.key -> "TIMESTAMP_NTZ") {
+      assert(df.selectExpr(s"to_timestamp(s, '$fmt', 9)", 
s"try_to_timestamp(s, '$fmt', 8)")
+        .schema.map(_.dataType) === Seq(TimestampNTZNanosType(9), 
TimestampNTZNanosType(8)))
+      assert(nanosDF(7).selectExpr("to_timestamp(ltz)", "try_to_timestamp(ltz, 
'yyyy')")
+        .schema.map(_.dataType) === Seq(TimestampNTZNanosType(7), 
TimestampNTZNanosType(7)))
+    }
+    // With a format, a numeric input is parsed as a string at every precision.
+    val parsedNumeric = Instant.parse("2020-01-01T08:00:00Z")
+    checkAnswer(
+      sql("SELECT to_timestamp_ltz(20200101, 'yyyyMMdd', 9), " +
+        "to_timestamp(20200101, 'yyyyMMdd', 8), try_to_timestamp(20200101, 
'yyyyMMdd', 7), " +
+        "to_timestamp_ltz(20200101, 'yyyyMMdd', 6)"),
+      Row(parsedNumeric, parsedNumeric, parsedNumeric, 
Timestamp.from(parsedNumeric)))
+  }
+
+  test("SPARK-57836: to_timestamp* with a precision on invalid input") {
+    import testImplicits._
+    val df = Seq("bad").toDF("s")
+    // try_to_timestamp is always NULL; the others fail in ANSI mode like the 
microsecond path.
+    checkAnswer(df.selectExpr("try_to_timestamp(s, 'yyyy', 9)"), Row(null))
+    toTimestampFns.filter(_ != "try_to_timestamp").foreach { fn =>
+      val res = df.selectExpr(s"$fn(s, 'yyyy', 9)")
+      if (conf.ansiEnabled) {
+        checkError(
+          exception = intercept[SparkDateTimeException](res.collect()),
+          condition = "CANNOT_PARSE_TIMESTAMP",
+          parameters = Map(
+            "func" -> "`try_to_timestamp`",
+            "message" -> "Text 'bad' could not be parsed at index 0"))
+      } else {
+        checkAnswer(res, Row(null))
+      }
+    }
+  }
+
+  test("SPARK-57836: to_timestamp* reject an invalid precision") {
+    val df = spark.range(1)
+    // A BIGINT precision does not wrap into range.
+    Seq(
+      ("to_timestamp", 5L, "TIMESTAMP_LTZ"),
+      ("try_to_timestamp", 0L, "TIMESTAMP_LTZ"),
+      ("to_timestamp_ntz", 10L, "TIMESTAMP_NTZ"),
+      ("to_timestamp_ltz", 4294967305L, "TIMESTAMP_LTZ")).foreach { case (fn, 
p, typeName) =>
+      checkError(
+        exception = intercept[SparkException](
+          df.selectExpr(s"$fn('2020', 'yyyy', $p)").collect()),
+        condition = "INVALID_TIMESTAMP_PRECISION",
+        parameters = Map("precision" -> p.toString, "type" -> typeName))
+    }
+    val nonFoldable = "to_timestamp('2020', 'yyyy', id)"
+    checkError(
+      exception = intercept[AnalysisException](df.selectExpr(nonFoldable)),
+      condition = "NON_FOLDABLE_ARGUMENT",
+      parameters = Map(
+        "funcName" -> "`to_timestamp`", "paramName" -> "`precision`", 
"paramType" -> "\"BIGINT\""),
+      context = ExpectedContext(fragment = nonFoldable, start = 0, stop = 
nonFoldable.length - 1))
+    val nonIntegral = "to_timestamp('2020', 'yyyy', '9')"
+    checkError(
+      exception = intercept[AnalysisException](df.selectExpr(nonIntegral)),
+      condition = "UNEXPECTED_INPUT_TYPE",
+      parameters = Map(
+        "paramIndex" -> "third",
+        "functionName" -> "`to_timestamp`",
+        "requiredType" -> "\"INT\"",
+        "inputSql" -> "\"9\"",
+        "inputType" -> "\"STRING\""),
+      context = ExpectedContext(fragment = nonIntegral, start = 0, stop = 
nonIntegral.length - 1))
+    val nullPrecision = "to_timestamp('2020', 'yyyy', CAST(NULL AS INT))"
+    checkError(
+      exception = intercept[AnalysisException](df.selectExpr(nullPrecision)),
+      condition = "DATATYPE_MISMATCH.UNEXPECTED_NULL",
+      parameters = Map("exprName" -> "`precision`", "sqlExpr" -> "\"CAST(NULL 
AS INT)\""),
+      context =
+        ExpectedContext(fragment = nullPrecision, start = 0, stop = 
nullPrecision.length - 1))
+    val tooManyArgs = "to_timestamp_ntz('2020', 'yyyy', 9, 9)"
+    checkError(
+      exception = intercept[AnalysisException](df.selectExpr(tooManyArgs)),
+      condition = "WRONG_NUM_ARGS.WITHOUT_SUGGESTION",
+      parameters = Map(
+        "functionName" -> "`to_timestamp_ntz`",
+        "expectedNum" -> "[1, 2, 3]",
+        "actualNum" -> "4",
+        "docroot" -> SPARK_DOC_ROOT),
+      context = ExpectedContext(fragment = tooManyArgs, start = 0, stop = 
tooManyArgs.length - 1))
+    withSQLConf(SQLConf.TIMESTAMP_NANOS_TYPES_ENABLED.key -> "false") {
+      checkError(
+        exception = intercept[SparkException](
+          df.selectExpr("to_timestamp_ltz('2020', 'yyyy', 9)").collect()),
+        condition = "FEATURE_NOT_ENABLED",
+        parameters = Map(
+          "featureName" -> "Nanosecond-precision timestamp types",
+          "configKey" -> "spark.sql.timestampNanosTypes.enabled",
+          "configValue" -> "true"))
+      // Precision 6 does not need the flag.
+      assert(df.selectExpr("to_timestamp('2020', 'yyyy', 
6)").schema.head.dataType ===
+        TimestampType)
+    }
+  }
+
+  test("SPARK-57836: to_timestamp* keep the precision of a 
nanosecond-precision input") {
+    Seq(7, 8, 9).foreach { p =>
+      val df = nanosDF(p)
+      val res = df.selectExpr(
+        "to_timestamp(ntz)", "to_timestamp_ntz(ltz)", "try_to_timestamp(ltz)",
+        "to_timestamp_ntz(ntz, 'yyyy')", "to_timestamp_ltz(ltz, 'yyyy')",
+        "to_timestamp(ntz, 'yyyy')", "to_timestamp_ntz(ltz, 'yyyy')")
+      assert(res.schema.map(_.dataType) === Seq(
+        TimestampLTZNanosType(p), TimestampNTZNanosType(p), 
TimestampLTZNanosType(p),
+        TimestampNTZNanosType(p), TimestampLTZNanosType(p),
+        TimestampLTZNanosType(p), TimestampNTZNanosType(p)))
+      // With or without a format, NTZ and LTZ convert in the session time 
zone (13:24:35 local).
+      val ntzNanos = nanoOfSecTruncator(p)(123456789)
+      val ltzNanos = nanoOfSecTruncator(p)(987654321)
+      val ntz = LocalDateTime.parse("2020-01-01T13:24:35").plusNanos(ntzNanos)
+      val ltz = Instant.parse("2020-01-01T21:24:35Z").plusNanos(ltzNanos)
+      val ntzAsLtz = Instant.parse("2020-01-01T21:24:35Z").plusNanos(ntzNanos)
+      val ltzAsNtz = 
LocalDateTime.parse("2020-01-01T13:24:35").plusNanos(ltzNanos)
+      checkAnswer(res, Seq(
+        Row(ntzAsLtz, ltzAsNtz, ltz, ntz, ltz, ntzAsLtz, ltzAsNtz),
+        Row(null, null, null, null, null, null, null)))
+    }
+    // An explicit precision converts a nanosecond input, flooring it when 
narrower.
+    val res =
+      nanosDF(9).selectExpr("to_timestamp_ntz(ntz, 'yyyy', 7)", 
"to_timestamp(ltz, 'yyyy', 6)")
+    assert(res.schema.map(_.dataType) === Seq(TimestampNTZNanosType(7), 
TimestampType))
+    checkAnswer(res, Seq(
+      Row(
+        LocalDateTime.parse("2020-01-01T13:24:35.123456700"),
+        Timestamp.from(Instant.parse("2020-01-01T21:24:35.987654Z"))),
+      Row(null, null)))
+  }
+
+  test("SPARK-57836: to_timestamp* cast a DATE or timestamp input to or from 
nanoseconds") {
+    // The format only applies to a string, so these match CAST in the session 
time zone.
+    val df = nanosDF(9).selectExpr(
+      "ntz", "ltz", "CAST(ntz AS TIMESTAMP_NTZ) AS ntz6", "CAST(ltz AS 
TIMESTAMP) AS ltz6",
+      "CAST(ltz AS DATE) AS d")
+    Seq("ntz", "ltz", "ntz6", "ltz6", "d").foreach { c =>
+      checkAnswer(
+        df.selectExpr(
+          s"to_timestamp($c, 'yyyy', 9)", s"to_timestamp_ltz($c, 'yyyy', 8)",
+          s"to_timestamp_ntz($c, 'yyyy', 7)", s"try_to_timestamp($c, 'yyyy', 
9)"),
+        df.selectExpr(
+          s"CAST($c AS TIMESTAMP_LTZ(9))", s"CAST($c AS TIMESTAMP_LTZ(8))",
+          s"CAST($c AS TIMESTAMP_NTZ(7))", s"CAST($c AS TIMESTAMP_LTZ(9))"))
+    }
+    Seq("ntz", "ltz").foreach { c =>
+      checkAnswer(
+        df.selectExpr(s"to_timestamp($c, 'yyyy', 6)", s"to_timestamp_ntz($c, 
'yyyy', 6)"),
+        df.selectExpr(s"CAST($c AS TIMESTAMP)", s"CAST($c AS TIMESTAMP_NTZ)"))
+    }
+    // Without a nanosecond input, precision 6 is the two-argument microsecond 
form.
+    Seq("ntz6", "ltz6", "d").foreach { c =>
+      checkAnswer(
+        df.selectExpr(s"to_timestamp($c, 'yyyy', 6)", s"to_timestamp_ntz($c, 
'yyyy', 6)"),
+        df.selectExpr(s"to_timestamp($c, 'yyyy')", s"to_timestamp_ntz($c, 
'yyyy')"))
+    }
+    // A DATE is midnight for TIMESTAMP_NTZ(p), not midnight in the session 
time zone.
+    checkAnswer(
+      sql("SELECT to_timestamp_ntz(DATE '2020-01-01', 'yyyy-MM-dd', 9)"),
+      Row(LocalDateTime.parse("2020-01-01T00:00:00")))
+  }
+
   test("typed Scala UDFs reject nanosecond inputs instead of narrowing them") {
     val ldt = LocalDateTime.parse("2020-01-01T12:00:00.123456789")
     val df = spark.createDataFrame(


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

Reply via email to