12

I'm using rust-chrono and I'm trying to parse a date like this:

extern crate chrono;

use chrono::*;

fn main() {

    let date_str = "2013-02-14 15:41:07";
    let date = DateTime::parse_from_str(&date_str, "%Y-%m-%d %H:%M:%S");
    match date {
        Ok(v) => println!("{:?}", v),
        Err(e) => println!("{:?}", e)
    }

}

And this is the output:

ParseError(NotEnough)

What does this mean? Not enough of what? Should I be using some other library?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Caballero
  • 11,546
  • 22
  • 103
  • 163

3 Answers3

11

Types that implement Error have more user-friendly error messages via Error::description or Display:

Err(e) => println!("{}", e)

This prints:

input is not enough for unique date and time

Presumably this is because you haven't provided a timezone, thus the time is ambiguous.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
4

You should use

UTC.datetime_from_str(&date_str, "%Y-%m-%d %H:%M:%S");

Like:

extern crate chrono;

use chrono::*;

fn main() {

    let date_str = "2013-02-14 15:41:07";
    let date = UTC.datetime_from_str(&date_str, "%Y-%m-%d %H:%M:%S");
    match date {
        Ok(v) => println!("{:?}", v),
        Err(e) => println!("{:?}", e)
    }

}
noshusan
  • 303
  • 2
  • 13
  • 1
    Updated: `NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S").map(|ndt| DateTime::::from_utc(ndt, Utc))` – Mingwei Samuel Jan 28 '20 at 21:43
  • @MingweiSamuel I'm guessing the update is due to "UTC" no longer being a part of Chrono? But is your suggestion seriously the most succinct way of parsing a datetime with a known timezone (that isn't included in the string)? I'm just a bit astounded as this seems like a fairly common need. – Brendano257 Dec 26 '20 at 13:25
  • It should be Utc: https://docs.rs/chrono/0.4.19/chrono/offset/struct.Utc.html – Marco Seravalli Jun 20 '21 at 18:23
1

The ParseError(NotEnough) shows up when there is not enough information to fill out the whole object. For example the date, time or timezone is missing.

In the example above the timezone is missing. So we can store it in a NaiveDateTime. This object does not store a timezone:

let naive_datetime = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S").unwrap();

For more info: https://stackoverflow.com/a/61179071/2037998

Ralph Bisschops
  • 1,888
  • 1
  • 22
  • 34