Skip to main content

try_to_time

Converts a column into TimeType using the optionally specified format. Specify formats according to datetime pattern. By default, it follows casting rules to TimeType if the format is omitted. Equivalent to col.cast("time"). The function always returns null on an invalid input.

Syntax

Python
import pyspark.sql.functions as sf

sf.try_to_time(str=<str>)

# With format
sf.try_to_time(str=<str>, format=<format>)

Parameters

Parameter

Type

Description

str

pyspark.sql.Column or str

String to be parsed to time.

format

pyspark.sql.Column or str

Optional. Time format pattern to follow.

Returns

pyspark.sql.Column: time value as pyspark.sql.types.TimeType type.

Examples

Example 1: Convert string to a time.

Python
import pyspark.sql.functions as sf
df = spark.createDataFrame([("10:30:00",)], ["str"])
df.select(sf.try_to_time(df.str).alias("time")).show()
Output
+--------+
| time|
+--------+
|10:30:00|
+--------+

Example 2: Convert string to a time with a format.

Python
import pyspark.sql.functions as sf
df = spark.createDataFrame([("10:30:00", "HH:mm:ss")], ["str", "format"])
df.select(sf.try_to_time(df.str, df.format).alias("time")).show()
Output
+--------+
| time|
+--------+
|10:30:00|
+--------+

Example 3: Conversion failure results in NULL.

Python
import pyspark.sql.functions as sf
df = spark.createDataFrame([("malformed",)], ["str"])
df.select(sf.try_to_time(df.str).alias("time")).show()
Output
+----+
|time|
+----+
|NULL|
+----+