Conversion string time data to Datetime

I need to convert time data column typed string to Datetime in Polars. But conversion failed
Typical string time data is : "2023-04-03T07:57:09Z"
. Here is the code snippet

        // Extract the "Date" column as a Series
        let date_series = df.column("Date").unwrap(); 
       // Apply DateTime::parse_from_rfc3339 to each value in the series
        // Iterate through the values in the Series
        for value in date_series.iter() {
                let value_str = value.to_string();
                let date_time = DateTime::parse_from_rfc3339(&value_str).unwrap();
                println!("Value: {}", date_time);
```. How can I solve the problem ?

What problem?

1 Like

It would be helpful to know how conversion failed. Maybe post some terminal output?

AnyValue has implemented Display so that it adds quotes when the value is a string, to differentiate it from other types. to_string uses Display to format the value.

AnyValue::String(v) => write!(f, "{}", format_args!("\"{v}\"")),

In general, you shouldn't use to_string when you want the actual data. There's a get_str method that lets you see the string data. It's also more efficient.

for value in date_series.iter() {
    let value_str = value.get_str().expect("value was not a string");
    let date_time = DateTime::parse_from_rfc3339(value_str).unwrap();
    println!("Value: {}", date_time);

P.S. be careful that the data isn't already a Datetime (I have no idea how to convert this).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.