Avançat

Datetime

When working with data, particularly in CSV files or databases, it’s common to find dates stored as strings.

We’ll guide learn how to convert strings to date or datetime in Polars with simple examples.

It’s important to understand that dates and times can be represented in various formats. Here are a few common string date formats:

  • YYYY-MM-DD (e.g., “2024-09-05”)
  • DD/MM/YYYY (e.g., “05/09/2024”)
  • YYYY-MM-DD HH:MM:SS (e.g., “2024-09-05 14:30:00”)

In Polars, a Date type stores only the date portion (year, month, and day), while Datetime includes both the date and time of day.

Before converting string columns to dates or datetimes, it is essential to load the data into a Polars DataFrame.

import polars as pl

data = {
    "id": [1, 2, 3],
    "date_str": ["2024-09-05", "2023-12-25", "2022-08-15"],
    "datetime_str": ["2024-09-05 14:30:00", "2023-12-25 18:45:00", "2022-08-15 09:15:00"]
}

Continua -> How to Convert String to Date or Datetime in Polars

Visualization

Docs

Plotly

Plotly can accept a Polars DataFrame by leveraging the dataframe interchange protocol, which offers zero-copy conversion where possible. Note that the protocol does not support all Polars data types (e.g. List) so your mileage may vary here.

import plotly.express as px

px.scatter(
    df,
    x="sepal_width",
    y="sepal_length",
    color="species",
    width=650,
    title="Irises",
    labels={'sepal_width': 'Sepal Width', 'sepal_length': 'Sepal Length'}
)