Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/sql-ref-ansi-compliance.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,7 @@ The behavior of some SQL functions can be different under ANSI mode (`spark.sql.
- `unix_timestamp`: This function should fail with an exception if the input string can't be parsed, or the pattern string is invalid.
- `to_unix_timestamp`: This function should fail with an exception if the input string can't be parsed, or the pattern string is invalid.
- `make_date`: This function should fail with an exception if the result date is invalid.
- `make_time`: This function should fail with an exception if the result time is invalid.
- `make_timestamp`: This function should fail with an exception if the result timestamp is invalid.
- `make_interval`: This function should fail with an exception if the result interval is invalid.
- `next_day`: This function throws `IllegalArgumentException` if input is not a valid day of week.
Expand All @@ -388,6 +389,7 @@ When ANSI mode is on, it throws exceptions for invalid operations. You can use t
- `try_make_timestamp`: identical to the function `make_timestamp`, except that it returns `NULL` result instead of throwing an exception on error.
- `try_make_timestamp_ltz`: identical to the function `make_timestamp_ltz`, except that it returns `NULL` result instead of throwing an exception on error.
- `try_make_timestamp_ntz`: identical to the function `make_timestamp_ntz`, except that it returns `NULL` result instead of throwing an exception on error.
- `try_make_time`: identical to the function `make_time`, except that it returns `NULL` result instead of throwing an exception on invalid inputs.
- `try_make_interval`: identical to the function `make_interval`, except that it returns `NULL` result instead of throwing an exception on invalid interval.
- `try_to_time`: identical to the function `to_time`, except that it returns `NULL` result instead of throwing an exception on string parsing error.
- `try_to_date`: identical to the function `to_date`, except that it returns `NULL` result instead of throwing an exception on string parsing error.
Expand Down
1 change: 1 addition & 0 deletions python/docs/source/reference/pyspark.sql/functions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ Date and Timestamp Functions
to_utc_timestamp
trunc
try_make_interval
try_make_time
try_make_timestamp
try_make_timestamp_ltz
try_make_timestamp_ntz
Expand Down
7 changes: 7 additions & 0 deletions python/pyspark/sql/connect/functions/builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4085,6 +4085,13 @@ def make_time(hour: "ColumnOrName", minute: "ColumnOrName", second: "ColumnOrNam
make_time.__doc__ = pysparkfuncs.make_time.__doc__


def try_make_time(hour: "ColumnOrName", minute: "ColumnOrName", second: "ColumnOrName") -> Column:
return _invoke_function_over_columns("try_make_time", hour, minute, second)


try_make_time.__doc__ = pysparkfuncs.try_make_time.__doc__


def time_from_seconds(col: "ColumnOrName") -> Column:
return _invoke_function_over_columns("time_from_seconds", col)

Expand Down
1 change: 1 addition & 0 deletions python/pyspark/sql/functions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@
"to_utc_timestamp",
"trunc",
"try_make_interval",
"try_make_time",
"try_make_timestamp",
"try_make_timestamp_ltz",
"try_make_timestamp_ntz",
Expand Down
48 changes: 48 additions & 0 deletions python/pyspark/sql/functions/builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -25580,6 +25580,54 @@ def make_time(hour: "ColumnOrName", minute: "ColumnOrName", second: "ColumnOrNam
return _invoke_function_over_columns("make_time", hour, minute, second)


@_try_remote_functions
def try_make_time(hour: "ColumnOrName", minute: "ColumnOrName", second: "ColumnOrName") -> Column:
"""
Try to create time from hour, minute and second fields.
The function returns NULL on invalid inputs.

.. versionadded:: 4.1.0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same versioning issue — update the Python versionadded to match (4.3.0). (The Connect builtin.py forwards __doc__, so no separate change is needed there.)

Suggested change
.. versionadded:: 4.1.0
.. versionadded:: 4.3.0


Parameters
----------
hour : :class:`~pyspark.sql.Column` or column name
The hour to represent, from 0 to 23.
minute : :class:`~pyspark.sql.Column` or column name
The minute to represent, from 0 to 59.
second : :class:`~pyspark.sql.Column` or column name
The second to represent, from 0 to 59.999999.

Returns
-------
:class:`~pyspark.sql.Column`
A column representing the created time, or NULL in case of an error.

See Also
--------
:meth:`pyspark.sql.functions.make_time`

Examples
--------
>>> from pyspark.sql import functions as sf
>>> df = spark.createDataFrame([(6, 30, 45.887)], ["hour", "minute", "second"])
>>> df.select(sf.try_make_time("hour", "minute", "second")).show()
+-----------------------------------+
|try_make_time(hour, minute, second)|
+-----------------------------------+
| 06:30:45.887|
+-----------------------------------+

>>> df = spark.createDataFrame([(25, 30, 0.0)], ["hour", "minute", "second"])
>>> df.select(sf.try_make_time("hour", "minute", "second")).show()
+-----------------------------------+
|try_make_time(hour, minute, second)|
+-----------------------------------+
| NULL|
+-----------------------------------+
"""
return _invoke_function_over_columns("try_make_time", hour, minute, second)


@_try_remote_functions
def time_from_seconds(col: "ColumnOrName") -> Column:
"""
Expand Down
17 changes: 17 additions & 0 deletions sql/api/src/main/scala/org/apache/spark/sql/functions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,23 @@ object functions {
Column.fn("make_time", hour, minute, second)
}

/**
* Try to create time from hour, minute and second fields. The function returns NULL on invalid
* inputs.
*
* @param hour
* the hour to represent, from 0 to 23
* @param minute
* the minute to represent, from 0 to 59
* @param second
* the second to represent, from 0 to 59.999999
* @group datetime_funcs
* @since 4.1.0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same versioning issue — update the Scala API @since to match (4.3.0, the branch-4.x version this ships in).

Suggested change
* @since 4.1.0
* @since 4.3.0

*/
def try_make_time(hour: Column, minute: Column, second: Column): Column = {
Column.fn("try_make_time", hour, minute, second)
}

/**
* Aggregate function: returns the most frequent value in a group.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,7 @@ object FunctionRegistry {
expression[WindowTime]("window_time"),
expression[MakeDate]("make_date"),
expression[MakeTime]("make_time"),
expressionBuilder("try_make_time", TryMakeTimeExpressionBuilder),
expression[TimeTrunc]("time_trunc"),
expression[TimeFromSeconds]("time_from_seconds"),
expression[TimeFromMillis]("time_from_millis"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,57 @@ case class MakeTime(
copy(hours = newChildren(0), minutes = newChildren(1), secsAndMicros = newChildren(2))
}

// scalastyle:off line.size.limit
@ExpressionDescription(
usage = "_FUNC_(hour, minute, second) - Try to create time from hour, minute and second fields. The function returns NULL on invalid inputs.",
arguments = """
Arguments:
* hour - the hour to represent, from 0 to 23
* minute - the minute to represent, from 0 to 59
* second - the second to represent, from 0 to 59.999999
""",
examples = """
Examples:
> SELECT _FUNC_(6, 30, 45.887);
06:30:45.887
> SELECT _FUNC_(NULL, 30, 0);
NULL
> SELECT _FUNC_(25, 30, 0);
NULL
""",
group = "datetime_funcs",
since = "4.1.0")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

try_make_time is a new function, but v4.1.0 is already released and does not contain it (it's absent from the v4.1.0 function registry). since should be the version this first ships in — branch-4.x = 4.3.0 (make_time/try_to_time legitimately say 4.1.0 because they shipped in that release; the value was likely copied from make_time).

Suggested change
since = "4.1.0")
since = "4.3.0")

If this is intended to be master-only (unusual for a new user-facing function), use 5.0.0 instead.

// scalastyle:on line.size.limit
object TryMakeTimeExpressionBuilder extends ExpressionBuilder {
override def build(funcName: String, expressions: Seq[Expression]): Expression = {
val numArgs = expressions.length
if (numArgs == 3) {
new TryMakeTime(expressions(0), expressions(1), expressions(2))
} else {
throw QueryCompilationErrors.wrongNumArgsError(funcName, Seq(3), numArgs)
}
}
}

case class TryMakeTime(
hours: Expression,
minutes: Expression,
secsAndMicros: Expression,
replacement: Expression)
extends RuntimeReplaceable with InheritAnalysisRules {

def this(hours: Expression, minutes: Expression, secsAndMicros: Expression) =
this(hours, minutes, secsAndMicros,
TryEval(MakeTime(hours, minutes, secsAndMicros)))

override def prettyName: String = "try_make_time"

override def parameters: Seq[Expression] = Seq(hours, minutes, secsAndMicros)

override protected def withNewChildInternal(newChild: Expression): TryMakeTime =
copy(replacement = newChild)
}

/**
* Adds day-time interval to time.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,44 @@ class TimeExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper {
)
}

test("creating values of TimeType via try_make_time") {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit (non-blocking): this test builds TryEval(MakeTime(...)) directly, so despite its title it doesn't instantiate the new TryMakeTime expression or TryMakeTimeExpressionBuilder. The class/builder are covered end-to-end by TimeFunctionsSuiteBase and the SQL golden, so coverage isn't missing — but constructing new TryMakeTime(...) here would make the unit test match its title and directly cover the new expression's plumbing (including the builder's arg-count error path, which nothing currently exercises).

// Valid cases should return the same result as make_time
checkEvaluation(
TryEval(MakeTime(Literal(13), Literal(2), Literal(Decimal(23.5, 16, 6)))),
LocalTime.of(13, 2, 23, 500000000))
checkEvaluation(
TryEval(MakeTime(Literal(0), Literal(0), Literal(Decimal(0.0, 16, 6)))),
LocalTime.of(0, 0, 0, 0))
checkEvaluation(
TryEval(MakeTime(Literal(23), Literal(59), Literal(Decimal(59.999999, 16, 6)))),
LocalTime.of(23, 59, 59, 999999000))

// Null cases
checkEvaluation(
TryEval(MakeTime(
Literal.create(null, IntegerType), Literal(18), Literal(Decimal(23.5, 16, 6)))),
null)
checkEvaluation(
TryEval(MakeTime(
Literal(13), Literal.create(null, IntegerType), Literal(Decimal(23.5, 16, 6)))),
null)
checkEvaluation(
TryEval(MakeTime(
Literal(13), Literal(18), Literal.create(null, DecimalType(16, 6)))),
null)

// Invalid cases return null instead of throwing
checkEvaluation(
TryEval(MakeTime(Literal(25), Literal(2), Literal(Decimal(23.5, 16, 6)))),
null)
checkEvaluation(
TryEval(MakeTime(Literal(23), Literal(-1), Literal(Decimal(23.5, 16, 6)))),
null)
checkEvaluation(
TryEval(MakeTime(Literal(23), Literal(12), Literal(Decimal(100.5, 16, 6)))),
null)
}

test("SecondExpressionBuilder") {
// Empty expressions list
checkError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2372,6 +2372,10 @@ class PlanGenerationTestSuite extends ConnectFunSuite with Logging {
fn.make_time(fn.lit(12), fn.lit(13), fn.lit(14))
}

temporalFunctionTest("try_make_time") {
fn.try_make_time(fn.lit(12), fn.lit(13), fn.lit(14))
}

temporalFunctionTest("current_time") {
fn.current_time()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Project [tryeval(static_invoke(DateTimeUtils.makeTime(12, 13, cast(14 as decimal(16,6))))) AS try_make_time(12, 13, 14)#0]
+- LocalRelation <empty>, [d#0, t#0, s#0, x#0L, wt#0]
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
{
"common": {
"planId": "1"
},
"project": {
"input": {
"common": {
"planId": "0"
},
"localRelation": {
"schema": "struct\u003cd:date,t:timestamp,s:string,x:bigint,wt:struct\u003cstart:timestamp,end:timestamp\u003e\u003e"
}
},
"expressions": [{
"unresolvedFunction": {
"functionName": "try_make_time",
"arguments": [{
"literal": {
"integer": 12
},
"common": {
"origin": {
"jvmOrigin": {
"stackTrace": [{
"classLoaderName": "app",
"declaringClass": "org.apache.spark.sql.functions$",
"methodName": "lit",
"fileName": "functions.scala"
}, {
"classLoaderName": "app",
"declaringClass": "org.apache.spark.sql.PlanGenerationTestSuite",
"methodName": "~~trimmed~anonfun~~",
"fileName": "PlanGenerationTestSuite.scala"
}]
}
}
}
}, {
"literal": {
"integer": 13
},
"common": {
"origin": {
"jvmOrigin": {
"stackTrace": [{
"classLoaderName": "app",
"declaringClass": "org.apache.spark.sql.functions$",
"methodName": "lit",
"fileName": "functions.scala"
}, {
"classLoaderName": "app",
"declaringClass": "org.apache.spark.sql.PlanGenerationTestSuite",
"methodName": "~~trimmed~anonfun~~",
"fileName": "PlanGenerationTestSuite.scala"
}]
}
}
}
}, {
"literal": {
"integer": 14
},
"common": {
"origin": {
"jvmOrigin": {
"stackTrace": [{
"classLoaderName": "app",
"declaringClass": "org.apache.spark.sql.functions$",
"methodName": "lit",
"fileName": "functions.scala"
}, {
"classLoaderName": "app",
"declaringClass": "org.apache.spark.sql.PlanGenerationTestSuite",
"methodName": "~~trimmed~anonfun~~",
"fileName": "PlanGenerationTestSuite.scala"
}]
}
}
}
}],
"isInternal": false
},
"common": {
"origin": {
"jvmOrigin": {
"stackTrace": [{
"classLoaderName": "app",
"declaringClass": "org.apache.spark.sql.functions$",
"methodName": "try_make_time",
"fileName": "functions.scala"
}, {
"classLoaderName": "app",
"declaringClass": "org.apache.spark.sql.PlanGenerationTestSuite",
"methodName": "~~trimmed~anonfun~~",
"fileName": "PlanGenerationTestSuite.scala"
}]
}
}
}
}]
}
}
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@
| org.apache.spark.sql.catalyst.expressions.TryDivide | try_divide | SELECT try_divide(3, 2) | struct<try_divide(3, 2):double> |
| org.apache.spark.sql.catalyst.expressions.TryElementAt | try_element_at | SELECT try_element_at(array(1, 2, 3), 2) | struct<try_element_at(array(1, 2, 3), 2):int> |
| org.apache.spark.sql.catalyst.expressions.TryMakeInterval | try_make_interval | SELECT try_make_interval(100, 11, 1, 1, 12, 30, 01.001001) | struct<try_make_interval(100, 11, 1, 1, 12, 30, 1.001001):interval> |
| org.apache.spark.sql.catalyst.expressions.TryMakeTimeExpressionBuilder | try_make_time | SELECT try_make_time(6, 30, 45.887) | struct<try_make_time(6, 30, 45.887):time(6)> |
| org.apache.spark.sql.catalyst.expressions.TryMakeTimestampExpressionBuilder | try_make_timestamp | SELECT try_make_timestamp(2014, 12, 28, 6, 30, 45.887) | struct<try_make_timestamp(2014, 12, 28, 6, 30, 45.887):timestamp> |
| org.apache.spark.sql.catalyst.expressions.TryMakeTimestampLTZExpressionBuilder | try_make_timestamp_ltz | SELECT try_make_timestamp_ltz(2014, 12, 28, 6, 30, 45.887) | struct<try_make_timestamp_ltz(2014, 12, 28, 6, 30, 45.887):timestamp> |
| org.apache.spark.sql.catalyst.expressions.TryMakeTimestampNTZExpressionBuilder | try_make_timestamp_ntz | SELECT try_make_timestamp_ntz(2014, 12, 28, 6, 30, 45.887) | struct<try_make_timestamp_ntz(2014, 12, 28, 6, 30, 45.887):timestamp_ntz> |
Expand Down
Loading