Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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
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.
import pyspark.sql.functions as sf
df = spark.createDataFrame([("10:30:00",)], ["str"])
df.select(sf.try_to_time(df.str).alias("time")).show()
+--------+
| time|
+--------+
|10:30:00|
+--------+
Example 2: Convert string to a time with a format.
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()
+--------+
| time|
+--------+
|10:30:00|
+--------+
Example 3: Conversion failure results in NULL.
import pyspark.sql.functions as sf
df = spark.createDataFrame([("malformed",)], ["str"])
df.select(sf.try_to_time(df.str).alias("time")).show()
+----+
|time|
+----+
|NULL|
+----+