pyspark.sql.functions.add_months

pyspark.sql.functions.add_months(start: ColumnOrName, months: Union[ColumnOrName, int]) → pyspark.sql.column.Column[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.

New in version 1.5.0.

Changed in version 3.4.0: Supports Spark Connect.

Parameters
startColumn or str

date column to work on.

monthsColumn or str or int

how many months after the given date to calculate. Accepts negative value as well to calculate backwards.

Returns
Column

a date after/before given number of months.

Examples

>>> df = spark.createDataFrame([('2015-04-08', 2)], ['dt', 'add'])
>>> df.select(add_months(df.dt, 1).alias('next_month')).collect()
[Row(next_month=datetime.date(2015, 5, 8))]
>>> df.select(add_months(df.dt, df.add.cast('integer')).alias('next_month')).collect()
[Row(next_month=datetime.date(2015, 6, 8))]
>>> df.select(add_months('dt', -2).alias('prev_month')).collect()
[Row(prev_month=datetime.date(2015, 2, 8))]