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.
12345678910111213141516171819import 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)
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat