Converting strings into date, time, and datetime
When you read in a dataset, you may find that columns that are supposed to be of the date
, time
, or datetime
data type are read as the string data type. You can try to fix that at the source or within your method such as .read_csv()
, but there are cases in which you don’t have that flexibility. The good news is that Polars has built-in methods to help convert strings into date
, time
, and datetime
values. You can apply those methods after reading in a dataset.
In this recipe, we’ll look at how we can utilize string methods such as .str.to_date()
, .str.to_time()
, .str.to_datetime()
, and .str.strptime()
.
How to do it...
Here’s how to utilize the methods to convert strings to date, time, or datetime values:
- Convert a string column to a date column:
df.select( 'at', pl.col('at').str.to_date(format='%Y-%m-%d %H:%M:%S').alias(...