Skip to main content
PYSPARK • LESSON 62

Extracting Calendar Month with month()

How do we extract the month number (1-12) from a date column for monthly partitioning?

Intermediate2 Minutes350 XP
🤔 THE QUESTION

How do we extract the month number (1-12) from a date column for monthly partitioning?

💡 WHAT IS IT?

month() extracts the month integer (1 to 12) from a date or timestamp Column.

🎯 WHAT IS IT USED FOR?

Monthly financial reporting, cohort retention tracking, and year-month hierarchical partitions.

💻 EXAMPLE
from pyspark.sql.functions import col, month

df = df.withColumn("order_month", month(col("order_date")))

🎯 Mission Objectives

Practice typing production-grade PySpark code for Extracting Calendar Month with month().

  • Import month function
  • Extract month integer (1-12)
  • Create monthly cohort partition key