Date and timestamp functions help us work with dates and times easily. They let us find differences, add time, or format dates in data.
Date and timestamp functions in Apache Spark
from pyspark.sql.functions import current_date, current_timestamp, datediff, date_add, date_sub, year, month, dayofmonth, to_date, unix_timestamp # Example usage: df.select(current_date(), current_timestamp()) df.select(datediff(df.end_date, df.start_date)) df.select(date_add(df.date, 5)) df.select(year(df.date))
Use from pyspark.sql.functions import <function_name> to access date functions.
Functions work on columns in Spark DataFrames, not on plain Python dates.
from pyspark.sql.functions import current_date df.select(current_date())
from pyspark.sql.functions import datediff df.select(datediff(df.end_date, df.start_date))
from pyspark.sql.functions import date_add df.select(date_add(df.date, 10))
from pyspark.sql.functions import year df.select(year(df.date))
This program creates a Spark DataFrame with start and end dates. It converts strings to dates, then calculates the difference in days, adds 5 days to the start date, extracts the year, and shows the current date and timestamp.
from pyspark.sql import SparkSession from pyspark.sql.functions import current_date, current_timestamp, datediff, date_add, year spark = SparkSession.builder.appName('DateExample').getOrCreate() # Create sample data data = [ ('2024-01-01', '2024-01-10'), ('2024-02-15', '2024-02-20') ] columns = ['start_date', 'end_date'] df = spark.createDataFrame(data, columns) # Convert string to date type from pyspark.sql.functions import to_date df = df.withColumn('start_date', to_date('start_date')) .withColumn('end_date', to_date('end_date')) # Calculate days difference result = df.select( 'start_date', 'end_date', datediff('end_date', 'start_date').alias('days_diff'), date_add('start_date', 5).alias('start_plus_5_days'), year('start_date').alias('start_year'), current_date().alias('today'), current_timestamp().alias('now') ) result.show(truncate=False) spark.stop()
Make sure date columns are in date format, not string, before using date functions.
Current date and timestamp depend on the system running Spark.
Use to_date() to convert strings to dates.
Date and timestamp functions help analyze and manipulate time data easily.
Common tasks include finding differences, adding days, and extracting parts like year or month.
Always convert strings to date type before using these functions in Spark.
Practice
current_date() return?Solution
Step 1: Understand the function purpose
current_date()returns the current date only, without any time information.Step 2: Compare with other date/time functions
current_timestamp()returns date and time, butcurrent_date()returns only the date part.Final Answer:
The current date without time part -> Option DQuick Check:
current_date() = date only [OK]
- Confusing current_date() with current_timestamp()
- Expecting time part in current_date() output
- Thinking it returns first or last day of month/year
date_col in Spark DataFrame?Solution
Step 1: Recall the correct function name and parameter order
The Spark function to add days isdate_add(date, days), where the first argument is the date column and second is number of days.Step 2: Check syntax correctness
df.withColumn('new_date', date_add(df.date_col, 5)) usesdate_add(df.date_col, 5)which matches the correct function and parameter order.Final Answer:
df.withColumn('new_date', date_add(df.date_col, 5)) -> Option AQuick Check:
date_add(date, days) = correct syntax [OK]
- Swapping parameter order in date_add
- Using non-existent function add_days or addDays
- Passing number before date column
df.show()?
from pyspark.sql.functions import to_date
data = [("2024-06-10",), ("2024-06-15",)]
df = spark.createDataFrame(data, ["date_str"])
df = df.withColumn("date", to_date(df.date_str))
df.show()Solution
Step 1: Understand to_date conversion
to_date()converts a string in 'yyyy-MM-dd' format to a date type successfully.Step 2: Check the input strings and output
Input strings are in correct format, sodatecolumn will have date values matching the strings.Final Answer:
DataFrame with date_str and date columns showing matching dates -> Option AQuick Check:
to_date('yyyy-MM-dd') converts string to date [OK]
- Expecting null output due to format mismatch
- Confusing date format output with slashes instead of dashes
- Thinking code causes syntax error
from pyspark.sql.functions import datediff
data = [("2024-06-10", "2024-06-15")]
df = spark.createDataFrame(data, ["start", "end"])
df = df.withColumn("diff", datediff(df.end, df.start))
df.show()Solution
Step 1: Check data types of columns
Columns "start" and "end" are strings in standard date format ('yyyy-MM-dd'), and Spark'sdatediff()can parse them implicitly without explicit conversion.Step 2: Verify function usage
datediff(df.end, df.start)has the correct parameter order (end first, start second) and computes the positive difference in days.Final Answer:
No error, code runs correctly and shows difference in days -> Option BQuick Check:
datediff on date-formatted strings works [OK]
- Thinking strings must be explicitly converted with to_date()
- Reversing datediff parameters
- Believing datediff requires timestamps only
event_time. You want to create a new column event_hour that extracts the hour of the day (0-23) from the timestamp. Which code snippet correctly achieves this?Solution
Step 1: Identify the correct function to extract hour
The Spark functionhour()extracts the hour (0-23) from a timestamp column.Step 2: Validate other options
extract_hour()does not exist;date_format()returns string, not integer;substring()on timestamp string is error-prone.Final Answer:
df.withColumn('event_hour', hour(df.event_time)) -> Option CQuick Check:
Use hour() to get hour from timestamp [OK]
- Using non-existent extract_hour function
- Using date_format returns string, not integer
- Using substring on timestamp string format
Ready to prove it?
Pass the test and this pattern moves unknown
