Skip to content

daft.functions.add_months#

add_months #

add_months(expr: Expression, months: Expression) -> Expression

Adds a number of months to a date or timestamp.

Mirrors Spark's add_months: when the start day exceeds the number of days in the resulting month, the result is clamped to the last day of that month. The return type is always Date, even when the input is a Timestamp (the time-of-day component is dropped before the shift).

Parameters:

Name Type Description Default
expr Expression

A Date or Timestamp expression.

required
months Expression

An integer expression for the number of months to add (may be negative).

required

Returns:

Name Type Description
Expression Expression

a Date expression shifted by the given number of months.

Examples:

1
2
3
4
5
6
>>> import daft
>>> from daft.functions import add_months
>>> df = daft.from_pydict({"d": ["2023-01-31", "2024-01-31"], "n": [1, 1]})
>>> df = df.with_column("d", df["d"].cast(daft.DataType.date()))
>>> df = df.with_column("result", add_months(df["d"], df["n"]))
>>> df.schema()["result"].dtype == daft.DataType.date()
True
Source code in daft/functions/datetime.py
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
def add_months(expr: Expression, months: Expression) -> Expression:
    """Adds a number of months to a date or timestamp.

    Mirrors Spark's ``add_months``: when the start day exceeds the number of days in
    the resulting month, the result is clamped to the last day of that month. The
    return type is always Date, even when the input is a Timestamp (the time-of-day
    component is dropped before the shift).

    Args:
        expr: A Date or Timestamp expression.
        months: An integer expression for the number of months to add (may be negative).

    Returns:
        Expression: a Date expression shifted by the given number of months.

    Examples:
        >>> import daft
        >>> from daft.functions import add_months
        >>> df = daft.from_pydict({"d": ["2023-01-31", "2024-01-31"], "n": [1, 1]})
        >>> df = df.with_column("d", df["d"].cast(daft.DataType.date()))
        >>> df = df.with_column("result", add_months(df["d"], df["n"]))
        >>> df.schema()["result"].dtype == daft.DataType.date()
        True
    """
    return Expression._call_builtin_scalar_fn("add_months", expr, months)