You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将形如"2020-04-12 22:10:57 UTC"的字符串转为Chrono::DateTime?

解决Chrono解析带UTC时区的DateTime字符串问题

你的代码报错是因为Chrono的%Z格式符不支持解析"UTC"这个时区标识,它仅对部分特定时区缩写(如EST、CET)有效,因此触发了NotEnough解析错误。以下是几种可行的修复方案:

方案1:直接将"UTC"作为格式的一部分匹配

不需要修改原字符串,直接在格式字符串里写死"UTC",配合Utc.datetime_from_str方法解析:

use chrono::{DateTime, Utc};

#[test]
fn t() {
    let date_str = "2020-04-12 22:10:57 UTC";
    // 直接把"UTC"纳入格式模板
    let datetime: DateTime<Utc> = Utc.datetime_from_str(date_str, "%Y-%m-%d %H:%M:%S UTC").unwrap();
    println!("{:?}", datetime);
}

方案2:先解析为NaiveDateTime再绑定UTC时区

截取原字符串中不带时区的部分,解析为无时区的NaiveDateTime,再手动绑定UTC时区:

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

#[test]
fn t() {
    let date_str = "2020-04-12 22:10:57 UTC";
    // 截取前19位(即"2020-04-12 22:10:57"部分)
    let naive_dt = NaiveDateTime::parse_from_str(&date_str[0..19], "%Y-%m-%d %H:%M:%S").unwrap();
    // 绑定UTC时区
    let datetime: DateTime<Utc> = DateTime::from_utc(naive_dt, Utc);
    println!("{:?}", datetime);
}

方案3:转换为RFC3339格式后解析

将原字符串转换为标准RFC3339格式(空格替换为T,UTC替换为Z),再用Chrono的RFC3339解析方法:

use chrono::{DateTime, Utc};

#[test]
fn t() {
    let date_str = "2020-04-12 22:10:57 UTC";
    // 转换为RFC3339格式:"2020-04-12T22:10:57Z"
    let rfc3339_str = date_str.replace(" ", "T").replace("UTC", "Z");
    let datetime: DateTime<Utc> = Utc::parse_from_rfc3339(&rfc3339_str).unwrap();
    println!("{:?}", datetime);
}

以上三种方案都能正确解析目标字符串为Chrono::DateTime<Utc>类型,可根据你的场景选择合适的方式。

内容的提问来源于stack exchange,提问作者grooby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:43:31