Built with Tutify.io

    AIStudyLabs

    How to Convert String to Date or Datetime in Polars

    How to Convert String to Date or Datetime in Polars

    In Polars, you can convert a string column to a Date or Datetime using the str.to_date() and str.to_datetime() methods. To transform a Polars string column into a datetime type (datetime[μs]), use str.to_datetime(). Likewise, to convert a string column into a date type (date), use str.to_date() method. In this article, I will explain converting strings to date or DateTime in Polars using simple examples.

    Key Points –

    <a id="h-quick-examples-of-convert-string-to-date-or-datetime"></a>

    Quick Examples of Convert String to Date or Datetime

    If you are in a hurry, below are some quick examples of how to convert string to date or datetime in polars.

    
    # Quick examples of converting string to date or datetime
    
    # Convert 'date_str' to Date type
    df2 = df.with_columns(
        pl.col("date_str").str.to_date().alias("date"))
    
    # Convert 'date_str' to Date with specified format
    df = df.with_columns(
        pl.col("date_str").str.strptime(pl.Date, "%Y-%m-%d").alias("date"))
    
    # Convert 'datetime_str' to Datetime type
    df2 = df.with_columns(
        pl.col("datetime_str").str.to_datetime().alias("datetime"))
    
    # Convert 'datetime_str' to Datetime type 
    # Using a custom format
    df2 = df.with_columns(
        pl.col("datetime_str").str.to_datetime(format="%Y-%m-%d %H:%M:%S").alias("datetime"))
    
    # Convert strings to date and datetime
    df2 = df.with_columns([
        pl.col("date_str").str.strptime(pl.Date, "%Y-%m-%d").alias("date"),
        pl.col("datetime_str").str.strptime(pl.Datetime, "%Y-%m-%d %H:%M:%S").alias("datetime")])
    
    # Convert string to date 
    # Using the custom format
    df2 = df.with_columns(
        pl.col("date_str").str.to_date("%d/%m/%Y").alias("custom_date"))
    
    # Convert string to datetime 
    # Using the custom format
    df = df.with_columns(
        pl.col("datetime_str").str.to_datetime("%d/%m/%Y %H:%M:%S").alias("custom_datetime"))
    

    To demonstrate how to convert a string to date or datetime in Polars, let's first create a Polars DataFrame.

    
    import polars as pl
    
    df = pl.DataFrame({
        'Courses':["Spark","PySpark", "Pandas"],
        'Fee' :[22000,25000,23000],
        "date_str": ["2024-01-20", "2023-12-15", "2025-06-10"],
        "datetime_str": ["2024-01-20 14:30:00", "2023-12-15 08:15:45", "2025-06-10 23:59:59"]})
    print("Original DataFrame:\n", df)
    

    Yields below output.

    <a id="h-converting-string-to-a-date-object"></a>

    Converting String to a Date Object

    To convert the date_str column from a string to a Date object, you can use the str.strptime() method with the appropriate date format in Polars.

    <a id="h-convert-string-to-date"></a>

    Convert String to Date

    To convert a string to a Date object in Polars, you can use the .str.to_date() method. This method automatically parses the string as a date, assuming the string is in a recognized date format (like "YYYY-MM-DD").

    
    # Convert 'date_str' to Date type
    df2 = df.with_columns(
        pl.col("date_str").str.to_date().alias("date"))
    print("Updated DataFrame with Date type:\n", df2)
    

    Here,

    <a id="h-specifying-the-format"></a>

    Specifying the Format

    When converting a string to a Date object in Polars, you can define the date string's format to align with the format of your data, ensuring accurate parsing.

    To convert string columns into date or datetime formats, with the pl.col().str.strptime() function facilitating the conversion. You can define the date format, such as %Y-%m-%d, which represents the year, month, and day format.

    
    # Convert 'date_str' to Date with specified format
    df = df.with_columns(
        pl.col("date_str").str.strptime(pl.Date, "%Y-%m-%d").alias("date"))
    print("Updated DataFrame with Date type:\n", df)
    
    # Output:
    # Updated DataFrame with Date type:
    # shape: (3, 5)
    ┌─────────┬───────┬────────────┬─────────────────────┬────────────┐
    │ Courses ┆ Fee   ┆ date_str   ┆ datetime_str        ┆ date       │
    │ ---     ┆ ---   ┆ ---        ┆ ---                 ┆ ---        │
    │ str     ┆ i64   ┆ str        ┆ str                 ┆ date       │
    ╞═════════╪═══════╪════════════╪═════════════════════╪════════════╡
    │ Spark   ┆ 22000 ┆ 2024-01-20 ┆ 2024-01-20 14:30:00 ┆ 2024-01-20 │
    │ PySpark ┆ 25000 ┆ 2023-12-15 ┆ 2023-12-15 08:15:45 ┆ 2023-12-15 │
    │ Pandas  ┆ 23000 ┆ 2025-06-10 ┆ 2025-06-10 23:59:59 ┆ 2025-06-10 │
    └─────────┴───────┴────────────┴─────────────────────┴────────────┘
    

    Here,

    <a id="h-converting-string-to-datetime"></a>

    Converting String to DateTime

    To convert a string to a DateTime object in Polars, you can use the str.to_datetime() method. This method automatically recognizes the standard datetime formats (such as "YYYY-MM-DD HH:MM:SS") and converts the string to a DateTime object.

    
    # Convert 'datetime_str' to Datetime type
    df2 = df.with_columns(
        pl.col("datetime_str").str.to_datetime().alias("datetime"))
    print("Updated DataFrame with Datetime type:\n", df2)
    
    # Output:
    # Updated DataFrame with Datetime type:
    # shape: (3, 5)
    ┌─────────┬───────┬────────────┬─────────────────────┬─────────────────────┐
    │ Courses ┆ Fee   ┆ date_str   ┆ datetime_str        ┆ datetime            │
    │ ---     ┆ ---   ┆ ---        ┆ ---                 ┆ ---                 │
    │ str     ┆ i64   ┆ str        ┆ str                 ┆ datetime[μs]        │
    ╞═════════╪═══════╪════════════╪═════════════════════╪═════════════════════╡
    │ Spark   ┆ 22000 ┆ 2024-01-20 ┆ 2024-01-20 14:30:00 ┆ 2024-01-20 14:30:00 │
    │ PySpark ┆ 25000 ┆ 2023-12-15 ┆ 2023-12-15 08:15:45 ┆ 2023-12-15 08:15:45 │
    │ Pandas  ┆ 23000 ┆ 2025-06-10 ┆ 2025-06-10 23:59:59 ┆ 2025-06-10 23:59:59 │
    └─────────┴───────┴────────────┴─────────────────────┴─────────────────────┘
    

    Here,

    <a id="h-specifying-the-datetime-format"></a>

    Specifying the Datetime Format

    To specify a custom datetime format in Polars, you can use the .str.to_datetime() method along with a format string. The format string should follow the strftime conventions, which allow you to specify the exact structure of the datetime string you're working with.

    
    # Convert 'datetime_str' to Datetime type 
    # Using a custom format
    df2 = df.with_columns(
        pl.col("datetime_str").str.to_datetime(format="%Y-%m-%d %H:%M:%S").alias("datetime")
    )
    print("Updated DataFrame with Datetime type:\n", df2)
    
    # Output:
    # Updated DataFrame with Datetime type:
    # shape: (3, 5)
    ┌─────────┬───────┬────────────┬─────────────────────┬─────────────────────┐
    │ Courses ┆ Fee   ┆ date_str   ┆ datetime_str        ┆ datetime            │
    │ ---     ┆ ---   ┆ ---        ┆ ---                 ┆ ---                 │
    │ str     ┆ i64   ┆ str        ┆ str                 ┆ datetime[μs]        │
    ╞═════════╪═══════╪════════════╪═════════════════════╪═════════════════════╡
    │ Spark   ┆ 22000 ┆ 2024-01-20 ┆ 2024-01-20 14:30:00 ┆ 2024-01-20 14:30:00 │
    │ PySpark ┆ 25000 ┆ 2023-12-15 ┆ 2023-12-15 08:15:45 ┆ 2023-12-15 08:15:45 │
    │ Pandas  ┆ 23000 ┆ 2025-06-10 ┆ 2025-06-10 23:59:59 ┆ 2025-06-10 23:59:59 │
    └─────────┴───────┴────────────┴─────────────────────┴─────────────────────┘
    

    Here,

    <a id="h-convert-strings-to-date-and-datetime"></a>

    Convert Strings to Date and DateTime

    You can use .str.strptime() to convert string columns into proper Date and Datetime types. Alternatively, the .str.to_date() and .str.to_datetime() methods provide a simple way to perform these conversions.

    
    # Convert strings to date and datetime
    df2 = df.with_columns([
        pl.col("date_str").str.strptime(pl.Date, "%Y-%m-%d").alias("date"),
        pl.col("datetime_str").str.strptime(pl.Datetime, "%Y-%m-%d %H:%M:%S").alias("datetime")
    ])
    print("DataFrame after conversion:\n", df2)
    
    # Output:
    # DataFrame after conversion:
    # shape: (3, 6)
    ┌─────────┬───────┬────────────┬─────────────────────┬────────────┬─────────────────────┐
    │ Courses ┆ Fee   ┆ date_str   ┆ datetime_str        ┆ date       ┆ datetime            │
    │ ---     ┆ ---   ┆ ---        ┆ ---                 ┆ ---        ┆ ---                 │
    │ str     ┆ i64   ┆ str        ┆ str                 ┆ date       ┆ datetime[μs]        │
    ╞═════════╪═══════╪════════════╪═════════════════════╪════════════╪═════════════════════╡
    │ Spark   ┆ 22000 ┆ 2024-01-20 ┆ 2024-01-20 14:30:00 ┆ 2024-01-20 ┆ 2024-01-20 14:30:00 │
    │ PySpark ┆ 25000 ┆ 2023-12-15 ┆ 2023-12-15 08:15:45 ┆ 2023-12-15 ┆ 2023-12-15 08:15:45 │
    │ Pandas  ┆ 23000 ┆ 2025-06-10 ┆ 2025-06-10 23:59:59 ┆ 2025-06-10 ┆ 2025-06-10 23:59:59 │
    └─────────┴───────┴────────────┴─────────────────────┴────────────┴─────────────────────┘
    

    <a id="h-converting-with-custom-formats"></a>

    Converting with Custom Formats

    In some cases, date and datetime strings may not follow the standard "YYYY-MM-DD" or "YYYY-MM-DD HH:MM:SS" formats. Polars allows you to specify a custom format using str.to_date(format) and str.to_datetime(format).

    <a id="h-convert-string-to-date-with-a-custom-format"></a>

    Convert String to Date with a Custom Format

    If your date strings are in a non-standard format (e.g., "DD/MM/YYYY" or "MM-DD-YYYY"), you can use str.to_date(format).

    
    import polars as pl
    
    df = pl.DataFrame({
        'Courses':["Spark","PySpark", "Pandas"],
        'Fee' :[22000,25000,23000],
        "date_str": ["20/01/2024", "15/12/2023", "10/06/2025"]})
    
    # Convert string to date using the custom format
    df2 = df.with_columns(
        pl.col("date_str").str.to_date("%d/%m/%Y").alias("custom_date")
    )
    print("Updated DataFrame with Custom Date Format:\n", df2)
    
    # Output:
    # Updated DataFrame with Custom Date Format:
    # shape: (3, 4)
    ┌─────────┬───────┬────────────┬─────────────┐
    │ Courses ┆ Fee   ┆ date_str   ┆ custom_date │
    │ ---     ┆ ---   ┆ ---        ┆ ---         │
    │ str     ┆ i64   ┆ str        ┆ date        │
    ╞═════════╪═══════╪════════════╪═════════════╡
    │ Spark   ┆ 22000 ┆ 20/01/2024 ┆ 2024-01-20  │
    │ PySpark ┆ 25000 ┆ 15/12/2023 ┆ 2023-12-15  │
    │ Pandas  ┆ 23000 ┆ 10/06/2025 ┆ 2025-06-10  │
    └─────────┴───────┴────────────┴─────────────┘
    

    Here,

    <a id="h-convert-string-to-datetime-with-a-custom-format"></a>

    Convert String to Datetime with a Custom Format

    If your datetime strings are in non-standard formats (e.g., "DD/MM/YYYY HH:MM:SS" or "MM-DD-YYYY HH:MM"), use str.to_datetime(format).

    
    import polars as pl
    
    df = pl.DataFrame({
        "Courses": ["Spark", "PySpark", "Pandas"],
        "Fee": [22000, 25000, 23000],
        "datetime_str": ["20/01/2024 14:30:00", "15/12/2023 08:15:45", "10/06/2025 23:59:59"]
    })
    
    # Convert string to datetime using the custom format
    df = df.with_columns(
        pl.col("datetime_str").str.to_datetime("%d/%m/%Y %H:%M:%S").alias("custom_datetime")
    )
    print("Updated DataFrame with Custom Datetime Format:\n", df)
    
    # Output:
    # Updated DataFrame with Custom Datetime Format:
    # shape: (3, 4)
    ┌─────────┬───────┬─────────────────────┬─────────────────────┐
    │ Courses ┆ Fee   ┆ datetime_str        ┆ custom_datetime     │
    │ ---     ┆ ---   ┆ ---                 ┆ ---                 │
    │ str     ┆ i64   ┆ str                 ┆ datetime[μs]        │
    ╞═════════╪═══════╪═════════════════════╪═════════════════════╡
    │ Spark   ┆ 22000 ┆ 20/01/2024 14:30:00 ┆ 2024-01-20 14:30:00 │
    │ PySpark ┆ 25000 ┆ 15/12/2023 08:15:45 ┆ 2023-12-15 08:15:45 │
    │ Pandas  ┆ 23000 ┆ 10/06/2025 23:59:59 ┆ 2025-06-10 23:59:59 │
    └─────────┴───────┴─────────────────────┴─────────────────────┘
    

    Here,

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

    Conclusion

    In summary, converting string data to date and datetime types in Polars is both simple and efficient, significantly improving the ability to work with temporal data. The str.to_date() and str.to_datetime() methods facilitate the easy transformation of string-based date and time values, unlocking more advanced capabilities for time-series analysis and temporal data operations.

    Happy Learning!!

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

    Related Articles

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

    References