chronotope / chrono

Date and time library for Rust
Other
3.3k stars 523 forks source link

"input is not enough" for DateTime::parse_from_str but works for Utc.datetime_from_str #1542

Closed JiveyGuy closed 6 months ago

JiveyGuy commented 6 months ago

Version: chrono = "0.4.35" Code:

use chrono::{DateTime, Utc, TimeZone};

fn main() {
    let time_str = "1882-12-19T13:18:57.000Z"; 
    let parse_from_str_result = DateTime::parse_from_str(time_str, "%Y-%m-%dT%H:%M:%S%.3fZ");
    let datetime_from_str = Utc.datetime_from_str(time_str, "%Y-%m-%dT%H:%M:%S%.3fZ");
    match parse_from_str_result {
        Ok(datetime) => {
            println!("Parsed datetime: {}", datetime);
        }
        Err(e) => {
            println!("Error parsing datetime: {}", e);
        }
    }
    match datetime_from_str {
        Ok(datetime) => {
            println!("Parsed datetime: {}", datetime);
        }
        Err(e) => {
            println!("Error parsing datetime: {}", e);
        }
    }
}

Output:

Error parsing datetime: input is not enough for unique date and time
Parsed datetime: 1882-12-19 13:18:57 UTC

What am I doing wrong? Or rather, is Datetime::parse_from_str broken?

pitdicker commented 6 months ago

What is missing is an offset. DateTime::parse_from_str expects the input to have a date, time and offset from UTC. Can you try parsing to a NaiveDateTime instead, which doesn't have this requirement, and then convert to a DateTime?

let parse_from_str_result = NaiveDateTime::parse_from_str(time_str, "%Y-%m-%dT%H:%M:%S%.3fZ").and_utc();

B.t.w. you may be better off using DateTime::parse_from_rfc3339. That is the format of your input string, and the specialized parser is faster and spec compliant.

JiveyGuy commented 6 months ago

Thanks that was the issue. I thought the ending Z was what was needed for TZ.