Reputation: 13
How to Convert a string like "2020-04-12 22:10:57 UTC" to Chrono::DateTime ?
Code:
#[test]
fn t() {
let date_str = "2020-04-12 22:10:57 UTC";
let datetime = DateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S %Z").unwrap();
println!("{:?}", datetime)
}
Error:
called `Result::unwrap()` on an `Err` value: ParseError(NotEnough)
thread 'types::date_time::t' panicked at src/types/date_time.rs:105:79:
called `Result::unwrap()` on an `Err` value: ParseError(NotEnough)
How to convert a String to a chrono::DateTime
Upvotes: 0
Views: 105
Reputation: 19
ParseError(NotEnough)
means that your timestamp is too ambiguous for chrono to construct a DateTime
. In this case, it seems that the timezone information is missing. Parsing timezone abbreviations is generally regarded as a challenging task. A single identifier may not be enough to uniquely identify a timezone. This likely causes the error you're getting
If you're certain that you need to be able to parse timestamps from different timezones, I recommend using %z (tz offset like +0000) instead of %Z (tz abbreviation like UTC). Otherwise, you could add the timezone manually (if you need it) like in the following code:
#[test]
fn parse_timestamp() {
use chrono::NaiveDateTime;
// Parse a timestamp without timezone information (`NaiveDateTime`)
let date_str = "2020-04-12 22:10:57";
let naive_date = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S")
.expect("Timestamps should conform to the used format");
// Apply a timezone to the timestamp to get a proper `DateTime`
// For other timezones, see `.and_local_timezone()` and the chrono_tz crate
let date = naive_date.and_utc();
println!("{:?}", date)
}
Upvotes: 1