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

  1. Raw string columns
  2. Trim spaces and fix case (trim, initcap, upper)
  3. Remove or extract patterns (regexp_replace, regexp_extract)
  4. Is it a date or time column? Yes: Parse with to_date / to_timestamp and a pattern. No: Keep as a clean string.
  5. Derive parts and gaps (year, date_format, datediff)
  6. 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

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic