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

如何在Rust的chrono库中显示不含小数秒的DateTime?

在Rust中移除chrono UTC时间的毫秒部分

直接使用{:?}打印chrono库的UTC当前时间时,输出会包含多余的毫秒小数:

println!("{:?}", chrono::offset::Utc::now());

输出示例:

2022-12-01T07:56:54.242352517Z

如果需要输出不带毫秒的格式:

2022-12-01T07:56:54Z

可以用以下两种方法实现:

方法1:自定义格式化输出

chrono支持通过format方法指定时间格式字符串,使用%Y-%m-%dT%H:%M:%SZ即可生成目标格式:

use chrono::Utc;

fn main() {
    let current_time = Utc::now();
    println!("{}", current_time.format("%Y-%m-%dT%H:%M:%SZ"));
}

方法2:截断时间的毫秒部分

如果需要得到一个本身就不含毫秒的DateTime对象(而非仅格式化输出),可以调用trunc_subsecs(0)方法截断所有小数秒:

use chrono::Utc;

fn main() {
    let current_time = Utc::now().trunc_subsecs(0);
    println!("{:?}", current_time);
}

此时用{:?}打印就不会显示毫秒部分了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:15:32