Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Dates & Times | Strings, Dates, Missing Data
Data Wrangling with Polars

Dates & Times

Swipe to show menu

When working with real-world datasets, you will often encounter date and time information stored as plain text. To analyze or manipulate these dates, you need to convert them into a datetime format that Polars can understand. In this chapter, you will learn how to parse release_date strings to datetime and extract the release year using the .dt namespace.

Suppose you have a DataFrame with a column called release_date, where each value is a string like "2015-07-14". To work with these as dates, you must first convert the column to a datetime type. Then, you can extract useful information, such as the year, using Polars' powerful .dt accessor.

12345678910111213141516171819
import polars as pl # Sample DataFrame with string dates df = pl.DataFrame({ "title": ["Movie A", "Movie B", "Movie C"], "release_date": ["2015-07-14", "2018-03-22", "2020-11-05"] }) # Convert 'release_date' to datetime df = df.with_columns( pl.col("release_date").str.strptime(pl.Date, "%Y-%m-%d").alias("release_date_dt") ) # Extract the release year as a new column df = df.with_columns( pl.col("release_date_dt").dt.year().alias("release_year") ) print(df)
question mark

Which Polars method is used to extract the year from a datetime column?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 3. Chapter 3
some-alt