Built with Tutify.io

    AIStudyLabs

    Retrieve Date from DateTime Column in Polars

    Retrieve Date from DateTime Column in Polars

    In polars, to retrieve the date from a datetime column, you can use the dt.date() method. This method extracts just the date (year, month, day) from a datetime column and removes the time portion (hours, minutes, seconds).

    Retrieving the date from a datetime column in Polars means extracting only the calendar date (in the format YYYY-MM-DD) from a column that includes both date and time information (such as 2025-05-08 14:30:00). In this article, I will explain retrieve the date from a datetime column in polars.

    Key Points –

    <a id="h-usage-of-retrieve-date-from-datetime-column"></a>

    Usage of Retrieve Date from DateTime Column

    To extract the date from a datetime column in Polars, you can use the dt.date() method. This method will extract just the date part (year, month, and day) from the datetime values, discarding the time portion.

    To run some examples of retrieving data from the datetime column in polars, let’s create a Polars DataFrame.

    
    import polars as pl
    import datetime as dt
    
    df = pl.DataFrame({
        "datetime_col": [dt.datetime(2025, 5, 8, 14, 30)]
    })
    print("Create DataFrame:\n", df)
    

    Yields below output.

    To create a DataFrame and extract the date from a datetime_col in Polars, you can use the dt accessor to access datetime functionalities and retrieve the date part.

    
    # Extract the date part from the datetime column
    df2 = df.with_columns(
        pl.col("datetime_col").dt.date().alias("date_only")
    )
    print("DataFrame with Extracted Date:\n", df2)
    

    Here,

    <a id="h-retrieve-date-and-keep-original"></a>

    Retrieve Date and Keep Original

    To extract the date from a datetime column and keep the original column in the Polars DataFrame, you can use the with_columns() function to add a new column without changing the existing one.

    
    import polars as pl
    import datetime as dt
    
    # Create a sample DataFrame
    df = pl.DataFrame({
        "datetime_col": [dt.datetime(2025, 5, 8, 14, 30), dt.datetime(2025, 5, 9, 10, 45)]
    })
    
    # Add a new column with only the date
    df2 = df.with_columns(
        pl.col("datetime_col").dt.date().alias("date_only")
    )
    print("Original datetime and extracted date:\n", df2)
    
    # Output:
    # Original datetime and extracted date:
    # shape: (2, 2)
    ┌─────────────────────┬────────────┐
    │ datetime_col        ┆ date_only  │
    │ ---                 ┆ ---        │
    │ datetime[μs]        ┆ date       │
    ╞═════════════════════╪════════════╡
    │ 2025-05-08 14:30:00 ┆ 2025-05-08 │
    │ 2025-05-09 10:45:00 ┆ 2025-05-09 │
    └─────────────────────┴────────────┘
    

    Here,

    <a id="h-rename-date-column-in-place"></a>

    Rename Date Column In-Place

    To rename the date column in-place (i.e., replace the original datetime column with just the date), you can apply dt.date() and use alias() with the same column name. Alternatively, to rename the date column while keeping the original datetime column unchanged in Polars, you can use the rename method.

    
    # Extract the date part and rename the column in place
    df_with_date = df.with_columns(df["datetime_col"].dt.date().alias("date_only")
    ).rename({"date_only": "extracted_date"})
    print("DataFrame with renamed date column:\n", df_with_date)
    
    # Output:
    # DataFrame with renamed date column:
    # shape: (2, 2)
    ┌─────────────────────┬────────────────┐
    │ datetime_col        ┆ extracted_date │
    │ ---                 ┆ ---            │
    │ datetime[μs]        ┆ date           │
    ╞═════════════════════╪════════════════╡
    │ 2025-05-08 14:30:00 ┆ 2025-05-08     │
    │ 2025-05-09 10:45:00 ┆ 2025-05-09     │
    └─────────────────────┴────────────────┘
    

    Here,

    <a id="h-create-a-dataframe-from-multiple-datetimes"></a>

    Create a DataFrame From Multiple Datetimes

    To extract the date from multiple datetime values in a Polars DataFrame while keeping the original datetime column intact, you can apply dt.date() to the relevant columns.

    
    import polars as pl
    import datetime as dt
    
    # Create a DataFrame with multiple datetime values
    df = pl.DataFrame({
        "datetime_col": [
            dt.datetime(2025, 1, 1, 10, 0),
            dt.datetime(2025, 2, 14, 18, 45),
            dt.datetime(2025, 5, 8, 9, 15)
        ]
    })
    
    # Extract only the date from each datetime
    df2 = df.with_columns(
        pl.col("datetime_col").dt.date().alias("date_only")
    )
    print("DataFrame with multiple datetimes and extracted dates:\n", df2)
    
    # Output:
    # DataFrame with multiple datetimes and extracted dates:
    # shape: (3, 2)
    ┌─────────────────────┬────────────┐
    │ datetime_col        ┆ date_only  │
    │ ---                 ┆ ---        │
    │ datetime[μs]        ┆ date       │
    ╞═════════════════════╪════════════╡
    │ 2025-01-01 10:00:00 ┆ 2025-01-01 │
    │ 2025-02-14 18:45:00 ┆ 2025-02-14 │
    │ 2025-05-08 09:15:00 ┆ 2025-05-08 │
    └─────────────────────┴────────────┘
    

    <a id="h-extract-year-month-day-separately"></a>

    Extract Year, Month, Day Separately

    To extract the year, month, and day separately from a datetime column in a Polars DataFrame, you can use the dt.year(), dt.month(), and dt.day() functions.

    
    import polars as pl
    import datetime as dt
    
    # Create a sample DataFrame with datetime values
    df = pl.DataFrame({
        "datetime_col": [
            dt.datetime(2025, 5, 8, 14, 30),
            dt.datetime(2025, 6, 15, 10, 45),
            dt.datetime(2026, 7, 20, 9, 15)
        ]
    })
    
    # Extract year, month, and day separately
    df2 = df.with_columns([
        pl.col("datetime_col").dt.year().alias("year"),
        pl.col("datetime_col").dt.month().alias("month"),
        pl.col("datetime_col").dt.day().alias("day")
    ])
    print("Extracted year, month, and day:\n", df2)
    
    # Output:
    # Extracted year, month, and day:
    # shape: (3, 4)
    ┌─────────────────────┬──────┬───────┬─────┐
    │ datetime_col        ┆ year ┆ month ┆ day │
    │ ---                 ┆ ---  ┆ ---   ┆ --- │
    │ datetime[μs]        ┆ i32  ┆ i8    ┆ i8  │
    ╞═════════════════════╪══════╪═══════╪═════╡
    │ 2025-05-08 14:30:00 ┆ 2025 ┆ 5     ┆ 8   │
    │ 2025-06-15 10:45:00 ┆ 2025 ┆ 6     ┆ 15  │
    │ 2026-07-20 09:15:00 ┆ 2026 ┆ 7     ┆ 20  │
    └─────────────────────┴──────┴───────┴─────┘
    

    Here,

    <a id="h-extract-date-then-filter"></a>

    Extract Date Then Filter

    To extract the date from a datetime column and filter the rows based on that date, you can first use the dt.date() method to extract the date, and then apply a condition to filter the DataFrame according to your criteria.

    
    import polars as pl
    import datetime as dt
    
    # Create DataFrame with multiple datetime values
    df = pl.DataFrame({
        "datetime_col": [
            dt.datetime(2025, 5, 8, 14, 30),
            dt.datetime(2024, 12, 25, 6, 45),
            dt.datetime(2023, 1, 1, 0, 0),
            dt.datetime(2022, 7, 15, 18, 20)
        ]
    })
    
    # Step 1: Extract date and add it as a new column
    df_with_date = df.with_columns(
        df["datetime_col"].dt.date().alias("date_only")
    )
    
    # Step 2: Filter the DataFrame based on the extracted date
    df2 = df_with_date.filter(df_with_date["date_only"] == dt.date(2024, 12, 25))
    print("Filtered DataFrame:\n", df2)
    
    # Output:
    # Filtered DataFrame:
    # shape: (1, 2)
    ┌─────────────────────┬────────────┐
    │ datetime_col        ┆ date_only  │
    │ ---                 ┆ ---        │
    │ datetime[μs]        ┆ date       │
    ╞═════════════════════╪════════════╡
    │ 2024-12-25 06:45:00 ┆ 2024-12-25 │
    └─────────────────────┴────────────┘
    

    Here,

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

    Conclusion

    In conclusion, extracting the date from a datetime column in Polars is simple and efficient using the dt.date() method. Whether you want to create a new column, replace the original, or filter based on date values, Polars offers clear and powerful tools to handle datetime operations with ease.

    Happy Learning!!

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

    Related Articles

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

    Reference