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

如何格式化std::chrono::time_point输出微秒/纳秒级高精度时间戳?

如何将std::chrono::time_point格式化为带微秒/纳秒精度的JSON时间戳

我正在编写将std::chrono::time_point对象序列化为JSON字符串的逻辑,现有代码如下:

std::string get_json(const std::chrono::time_point<std::chrono::system_clock> timestamp) {

    std::string result = std::format(
        "{{\r\n\"timestamp\": \"{%FT%T%z}\"\r\n}}",
        timestamp
    );

    return result;
}

其中使用\r\n是因为数据将发送至HTTP接口。我找到了介绍std::chrono::sys_time的std::formatter文档页面,但未找到针对std::chrono::time_point的相关内容,推测格式说明符相同。当前代码仅能输出如2025-03-08T19:54:00+0000的秒级时间戳,无法输出2025-03-08T19:54:00.123456+0000这类更高精度的格式。请问是否有办法实现微秒或纳秒级的格式化输出?(注:我并非询问特定时钟的最高分辨率,而是时钟值格式化的最高精度)


要输出微秒或纳秒级精度的时间戳,只需修改std::format的格式说明符,在秒的部分补充精度标识即可:

  • 微秒精度:使用%FT%T.%f%z格式,其中%f会固定输出6位微秒数字(不足时自动补0)。修改后的代码如下:

    std::string get_json(const std::chrono::time_point<std::chrono::system_clock> timestamp) {
        std::string result = std::format(
            "{{\r\n\"timestamp\": \"{%FT%T.%f%z}\"\r\n}}",
            timestamp
        );
        return result;
    }
    

    输出示例:2025-03-08T19:54:00.123456+0000

  • 纳秒精度:如果需要纳秒级显示,可使用%FT%T.%9f%z格式,%9f会输出9位纳秒数字:

    std::string get_json(const std::chrono::time_point<std::chrono::system_clock> timestamp) {
        std::string result = std::format(
            "{{\r\n\"timestamp\": \"{%FT%T.%9f%z}\"\r\n}}",
            timestamp
        );
        return result;
    }
    

    输出示例:2025-03-08T19:54:00.123456789+0000

另外你之前的推测完全正确:std::chrono::time_point<std::chrono::system_clock>本质就是std::chrono::sys_time的别名,所以std::formatter对sys_time的格式规则完全适用于它。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 01:14:53