String & Date Functions
Apache Spark · Cleaning & Complex Types
Theory
pyspark.sql.functions has hundreds of built-in string and date functions that run inside the JVM, so they are fast and null-safe. Common string functions: trim, lower, upper, initcap, length, substring, concat and concat_ws, lpad, split, regexp_replace (clean characters) and regexp_extract (pull a pattern such as a PIN code). For example F.initcap(F.trim("name")) turns " asha SHARMA " into "Asha Sharma".
For dates, convert strings first: F.to_date("d", "dd-MM-yyyy") and F.to_timestamp("ts", "yyyy-MM-dd HH:mm") parse with a pattern, and the try_ variants such as F.try_to_timestamp return null for bad values instead of failing in ANSI mode. Then use year, month, dayofweek, date_format (to text such as "MMM yyyy"), datediff, months_between, date_add, add_months, date_trunc("month", ts) and last_day. Always store dates as date or timestamp types, not strings, so comparisons and partition filters work.
Why we use it
Text fields arrive with stray spaces, mixed case and odd formats, and dates arrive as strings in many patterns. Built-in functions clean and convert them correctly at scale, and they let Spark optimise the query, which a Python loop or UDF would block.
When to use it
Use these functions in every cleaning step before joins and grouping (trim and case-fold join keys). Prefer built-ins over UDFs for any string or date logic. When input formats are inconsistent, parse with try_to_timestamp or try_to_date and route rows that come back null to a reject table.
How it works
- Raw string columns
- Trim spaces and fix case (trim, initcap, upper)
- Remove or extract patterns (regexp_replace, regexp_extract)
- Is it a date or time column? Yes: Parse with to_date / to_timestamp and a pattern. No: Keep as a clean string.
- Derive parts and gaps (year, date_format, datediff)
- Typed, clean columns ready for joins
Syntax
F.trim(c); F.initcap(c); F.upper(c); F.regexp_replace(c, r"[^0-9]", "")
F.regexp_extract(c, r"(\d{6})", 1); F.split(c, ","); F.concat_ws(" ", a, b)
F.to_date(c, "dd-MM-yyyy"); F.date_format(c, "MMM yyyy")
F.datediff(end, start); F.date_trunc("month", ts); F.add_months(d, 1)Example
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("techtown-spark").getOrCreate()
raw = spark.createDataFrame([
(101, " asha SHARMA ", "jaipur ", "+91 98290-11111", "05-01-2026"),
(102, "RAVI kumar", " PUNE", "97720 22222", "06-01-2026"),
(103, "meera iyer", "Delhi", "(91) 99880 33333", "07-01-2026"),
], "customer_id INT, name STRING, city STRING, phone STRING, order_date STRING")
clean = (raw
.withColumn("name", F.initcap(F.regexp_replace(F.trim("name"), r"\s+", " ")))
.withColumn("city", F.upper(F.trim("city")))
.withColumn("phone_digits", F.regexp_replace("phone", r"[^0-9]", ""))
.withColumn("last10", F.substring("phone_digits", -10, 10))
.withColumn("order_date", F.to_date("order_date", "dd-MM-yyyy"))
.withColumn("month", F.date_format("order_date", "MMM yyyy"))
.withColumn("weekday", F.date_format("order_date", "EEEE"))
.withColumn("days_ago", F.datediff(F.lit("2026-02-01").cast("date"), "order_date")))
clean.drop("phone").show(truncate=False)
# Output:
# +-----------+-----------+------+----------+------------+----------+--------+---------+--------+
# |customer_id|name |city |order_date|phone_digits|last10 |month |weekday |days_ago|
# +-----------+-----------+------+----------+------------+----------+--------+---------+--------+
# |101 |Asha Sharma|JAIPUR|2026-01-05|919829011111|9829011111|Jan 2026|Monday |27 |
# |102 |Ravi Kumar |PUNE |2026-01-06|9772022222 |9772022222|Jan 2026|Tuesday |26 |
# |103 |Meera Iyer |DELHI |2026-01-07|919988033333|9988033333|Jan 2026|Wednesday|25 |
# +-----------+-----------+------+----------+------------+----------+--------+---------+--------+
Key points
- Trim and case-fold text keys before joins, or 'Pune ' will not match 'Pune'
- Parse strings to date/timestamp early with an explicit pattern
- try_to_timestamp / try_to_date give null for bad input instead of an error
- date_format turns dates into display text; keep the real date column too
- regexp_replace and regexp_extract handle most cleaning without a UDF