pyspark.sql.functions.add_months#

pyspark.sql.functions.add_months(start, months)[source]#

Returns the date that is months months after start. If months is a negative value then these amount of months will be deducted from the start.

Added in version 1.5.0.

Changed in version 3.4.0: Supports Spark Connect.

Parameters:
startColumn or column name

date column to work on. A column that evaluates to a date.

monthsColumn or column name or int

how many months after the given date to calculate. Accepts negative value as well to calculate backwards. A column that evaluates to an integer.

Returns:
Column

a date after/before given number of months. Returns a column that evaluates to a date.

Examples

>>> import pyspark.sql.functions as sf
>>> df = spark.createDataFrame([('2015-04-08', 2,)], 'struct<dt:string,a:int>')
>>> df.select('*', sf.add_months(df.dt, 1)).show()
+----------+---+-----------------+
|        dt|  a|add_months(dt, 1)|
+----------+---+-----------------+
|2015-04-08|  2|       2015-05-08|
+----------+---+-----------------+
>>> df.select('*', sf.add_months('dt', 'a')).show()
+----------+---+-----------------+
|        dt|  a|add_months(dt, a)|
+----------+---+-----------------+
|2015-04-08|  2|       2015-06-08|
+----------+---+-----------------+
>>> df.select('*', sf.add_months('dt', sf.lit(-1))).show()
+----------+---+------------------+
|        dt|  a|add_months(dt, -1)|
+----------+---+------------------+
|2015-04-08|  2|        2015-03-08|
+----------+---+------------------+