Built with Tutify.io

    AIStudyLabs

    Polars Adding Days to a Date

    Polars Adding Days to a Date

    In Polars, adding days to a date refers to updating a Date or Datetime column (or value) by increasing or decreasing it by a specific number of days. This is accomplished using time durations, which represent intervals like days, hours, or minutes. It's particularly useful for tasks such as scheduling, forecasting, or adjusting timelines. The operation is typically performed using pl.col() combined with pl.duration() for clear and efficient time-based data manipulation. In this article, I will explain how to add days to a date in polars.

    Key Points –

    <a id="h-usage-of-polars-adding-days-to-a-date"></a>

    Usage of Polars Adding Days to a Date

    To add days to a date column in Polars, you can use the pl.duration() function to create a duration and then add that to the date column.

    Now, let’s create a Polars DataFrame.

    
    import polars as pl
    from datetime import date
    
    # Create a DataFrame with a date column
    df = pl.DataFrame({
        "start_date": [date(2024, 1, 5), date(2024, 5, 10), date(2024, 12, 31)]
    })
    print("Original DataFrame:\n", df)
    

    Yields below output.

    To add a fixed number of days (e.g., 10 days) to a date column in a Polars DataFrame, use the pl.duration() function to create a day-based duration and add it directly to the date column.

    
    # Add 10 days to each date in the "start_date" column
    df2 = df.with_columns(
        (pl.col("start_date") + pl.duration(days=10)).alias("new_date")
    )
    print("DataFrame with 10 days added:\n", df2)
    

    Here,

    <a id="h-add-negative-days-subtract-days"></a>

    Add Negative Days (Subtract Days)

    You can subtract a fixed number of days (e.g., 5 days) from a date column in Polars by passing a negative value to pl.duration(days=…).

    
    # Subtract 5 days from each date
    df = df.with_columns(
        (pl.col("start_date") + pl.duration(days=-5)).alias("minus_5_days")
    )
    print("DataFrame with 5 days subtracted:\n", df)
    
    # Output:
    # DataFrame with 5 days subtracted:
    # shape: (3, 2)
    ┌────────────┬──────────────┐
    │ start_date ┆ minus_5_days │
    │ ---        ┆ ---          │
    │ date       ┆ date         │
    ╞════════════╪══════════════╡
    │ 2024-01-05 ┆ 2023-12-31   │
    │ 2024-05-10 ┆ 2024-05-05   │
    │ 2024-12-31 ┆ 2024-12-26   │
    └────────────┴──────────────┘
    

    Here,

    <a id="h-add-days-based-on-a-variable-value"></a>

    Add Days Based on a Variable Value

    You can add days to a date column in Polars based on a variable by defining the value (e.g., days_to_add = 15) and using it with pl.duration(days=days_to_add).

    
    # Define variable
    days_to_add = 15
    
    # Add variable number of days
    df = df.with_columns(
        (pl.col("start_date") + pl.duration(days=days_to_add)).alias("plus_variable_days")
    )
    print("Days added using variable:\n", df)
    
    # Output:
    # Days added using variable:
    # shape: (3, 2)
    ┌────────────┬────────────────────┐
    │ start_date ┆ plus_variable_days │
    │ ---        ┆ ---                │
    │ date       ┆ date               │
    ╞════════════╪════════════════════╡
    │ 2024-01-05 ┆ 2024-01-20         │
    │ 2024-05-10 ┆ 2024-05-25         │
    │ 2024-12-31 ┆ 2025-01-15         │
    └────────────┴────────────────────┘
    

    Here,

    <a id="h-add-fractional-days-representing-hours-and-minutes"></a>

    Add Fractional Days (Representing Hours and Minutes)

    Polars allows you to add fractional days by converting them into hours, minutes, or seconds using the pl.duration() function. While you can't use decimal days directly, you can achieve the same effect by specifying the corresponding time units.

    
    # Add 1.5 days as 36 hours
    df2 = df.with_columns(
        (pl.col("start_date") + pl.duration(hours=36)).alias("plus_1_5_days")
    )
    print("DataFrame with 1.5 days added:\n", df2)
    
    # Output:
    # DataFrame with 1.5 days added:
    # shape: (3, 2)
    ┌────────────┬───────────────┐
    │ start_date ┆ plus_1_5_days │
    │ ---        ┆ ---           │
    │ date       ┆ date          │
    ╞════════════╪═══════════════╡
    │ 2024-01-05 ┆ 2024-01-06    │
    │ 2024-05-10 ┆ 2024-05-11    │
    │ 2024-12-31 ┆ 2025-01-01    │
    └────────────┴───────────────┘
    

    Here,

    <a id="h-add-days-using-a-column-value-dynamic-addition"></a>

    Add Days Using a Column Value (Dynamic Addition)

    To dynamically add days based on a column value (i.e., using the value from another column to determine the number of days to add), you can directly reference that column and pass it to the pl.duration() function.

    
    import polars as pl
    from datetime import date
    
    # Create a DataFrame with start_date and days_to_add columns
    df = pl.DataFrame({
        "start_date": [date(2025, 1, 1), date(2025, 5, 10), date(2025, 12, 31)],
        "days_to_add": [5, 10, 15]
    })
    
    # Dynamically add days from the "days_to_add" column
    df2 = df.with_columns(
        (pl.col("start_date") + pl.duration(days=pl.col("days_to_add"))).alias("new_date")
    )
    print("DataFrame with dynamic days added:\n", df2)
    
    # Output:
    # DataFrame with dynamic days added:
    # shape: (3, 3)
    ┌────────────┬─────────────┬────────────┐
    │ start_date ┆ days_to_add ┆ new_date   │
    │ ---        ┆ ---         ┆ ---        │
    │ date       ┆ i64         ┆ date       │
    ╞════════════╪═════════════╪════════════╡
    │ 2025-01-01 ┆ 5           ┆ 2025-01-06 │
    │ 2025-05-10 ┆ 10          ┆ 2025-05-20 │
    │ 2025-12-31 ┆ 15          ┆ 2026-01-15 │
    └────────────┴─────────────┴────────────┘
    

    Here,

    <a id="h-add-days-from-a-calculated-expression-e-g-multiplying-a-number"></a>

    Add Days from a Calculated Expression (e.g., Multiplying a Number)

    You can add days in Polars using a calculated expression, such as multiplying a numeric column by a constant. This is useful when the number of days to add is computed rather than fixed.

    
    import polars as pl
    from datetime import date
    
    # Create the DataFrame with a numeric column
    df = pl.DataFrame({
        "start_date": [date(2025, 2, 5), date(2025, 6, 10), date(2025, 10, 21)],
        "base_value": [3, 5, 7]  # Each row will add base_value * 2 days
    })
    
    # Add days from a calculated expression
    df = df.with_columns(
        (pl.col("start_date") + pl.duration(days=pl.col("base_value") * 2)).alias("new_date")
    )
    print("Days added using calculated expression:\n", df)
    
    # Output:
    # Days added using calculated expression:
    # shape: (3, 3)
    ┌────────────┬────────────┬────────────┐
    │ start_date ┆ base_value ┆ new_date   │
    │ ---        ┆ ---        ┆ ---        │
    │ date       ┆ i64        ┆ date       │
    ╞════════════╪════════════╪════════════╡
    │ 2025-02-05 ┆ 3          ┆ 2025-02-11 │
    │ 2025-06-10 ┆ 5          ┆ 2025-06-20 │
    │ 2025-10-21 ┆ 7          ┆ 2025-11-04 │
    └────────────┴────────────┴────────────┘
    

    Here,

    <a id="h-conclusion"></a>

    Conclusion

    In conclusion, adding days to a date column in Polars is straightforward and highly flexible. Whether you're working with a fixed value, a variable, another column, or a dynamically calculated expression, pl.duration() offers a clean and efficient solution. It provides precise control over date operations, making time-based data manipulation in large datasets both fast and intuitive.

    Happy Learning!!

    <a id="h-related-articles"></a>

    Related Articles

    <a id="h-reference"></a>

    Reference