On this page
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
Histogram
Polars has a built-in histogram method for a Series/column. The output is a DataFrame with the count data
It’s straightforward to use - just call .hist on a Series (or a column in a DataFrame). You can pass in a list of bin boundaries if you want more control.
To sound like a waiter in a fancy restaurant: the hist method works really well paired with an Altair chart which now also works natively with Polars!
df[ "unit price"].hist( bins=range(0,4000,50))
alt.Chart( df[ "unit price" ].hist( bins=range(0,4000,500) ), height=260).mark_bar().encode( x="unit price_count:Q", y=alt.Y("category:N", sort=alt.EncodingSortField(field="break_point")))