pyspark.sql.functions.months_between#
- pyspark.sql.functions.months_between(date1, date2, roundOff=True)[source]#
Returns number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. A whole number is returned if both inputs have the same day of month or both are the last day of their respective months. Otherwise, the difference is calculated assuming 31 days per month. The result is rounded off to 8 digits unless roundOff is set to False.
Added in version 1.5.0.
Changed in version 3.4.0: Supports Spark Connect.
- Parameters:
- date1
Columnor column name first date column. A column that evaluates to a timestamp.
- date2
Columnor column name second date column. A column that evaluates to a timestamp.
- roundOffbool, optional
whether to round (to 8 digits) the final value or not (default: True). A column that evaluates to a boolean.
- date1
- Returns:
Columnnumber of months between two dates. Returns a column that evaluates to a double.
Examples
>>> import pyspark.sql.functions as sf >>> df = spark.createDataFrame([('1997-02-28 10:30:00', '1996-10-30')], ['d1', 'd2']) >>> df.select('*', sf.months_between(df.d1, df.d2)).show() +-------------------+----------+----------------------------+ | d1| d2|months_between(d1, d2, true)| +-------------------+----------+----------------------------+ |1997-02-28 10:30:00|1996-10-30| 3.94959677| +-------------------+----------+----------------------------+
>>> df.select('*', sf.months_between('d2', 'd1')).show() +-------------------+----------+----------------------------+ | d1| d2|months_between(d2, d1, true)| +-------------------+----------+----------------------------+ |1997-02-28 10:30:00|1996-10-30| -3.94959677| +-------------------+----------+----------------------------+
>>> df.select('*', sf.months_between('d1', df.d2, False)).show() +-------------------+----------+-----------------------------+ | d1| d2|months_between(d1, d2, false)| +-------------------+----------+-----------------------------+ |1997-02-28 10:30:00|1996-10-30| 3.9495967741935...| +-------------------+----------+-----------------------------+