[英]BadFormat parsing string to date when using Chrono
I am trying to convert a string to a date using the Chrono library.我正在尝试使用 Chrono 库将字符串转换为日期。 I always get a BadFormat
or NotEnough
error:我总是收到BadFormat
或NotEnough
错误:
extern crate chrono;
use chrono::prelude::*;
fn main() {
let dt1 = DateTime::parse_from_str(
"2017-08-30 18:34:06.638997932 UTC",
"%Y-%m-%d %H:%M:%S.%9f"
);
println!("{:?}", dt1);
}
I'm not sure what I am doing wrong.我不确定我做错了什么。
As mentioned in the comments, your format string doesn't allow for the " UTC"
part of your string.如评论中所述,您的格式字符串不允许使用字符串的" UTC"
部分。 That's why you get the BadFormat
error.这就是您收到BadFormat
错误的原因。
If you add " UTC"
to your format string, you still get a BadFormat
error because you've typed .%9f
when it should be %.9f
.如果您在格式字符串中添加" UTC"
,您仍然会收到BadFormat
错误,因为您输入了.%9f
,而它应该是%.9f
。
Once you fix that, you get a NotEnough
error because we aren't actually parsing a timezone.一旦你解决了这个问题,你会得到一个NotEnough
错误,因为我们实际上并没有解析时区。
I'd use NaiveDateTime
to always parse in UTC and then add the " UTC"
onto the format string to ignore it, correcting the typo:我会使用NaiveDateTime
始终以 UTC 解析,然后将" UTC"
添加到格式字符串中以忽略它,更正错字:
use chrono::prelude::*; // 0.4.9
fn main() {
let dt1 = NaiveDateTime::parse_from_str(
"2017-08-30 18:34:06.638997932 UTC",
"%Y-%m-%d %H:%M:%S%.9f UTC",
);
println!("{:?}", dt1); // Ok(2017-08-30T18:34:06.638997932)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.