簡體   English   中英

如何使用 fmt 庫以小數秒打印當前時間

[英]How to print the current time with fractional seconds, using fmt library

這段代碼

#include <chrono>
#include <fmt/format.h>
#include <fmt/chrono.h>
...
auto now = std::chrono::system_clock::now();
fmt::print("The time is: {:%Y-%m-%d %H:%M:%S}\n", now);

打印這個:

時間是:2023-01-02 15:51:23

如何讓它打印亞秒級精度,例如毫秒? 就像是:

時間是:2023-01-02 15:51:23.753

我認為您必須分兩步執行此操作——YMD 和 HM,然后是高分辨率秒數。 這是一個有效的示例,在 Ubuntu 上使用fmt 9.0 版:

#include <chrono>
#include <fmt/format.h>
#include <fmt/chrono.h>

int main() {
    auto now = std::chrono::system_clock::now();
    auto sse = now.time_since_epoch();
    fmt::print("{:%FT%H:%M:}{:%S}\n", now, sse);
    exit(0);
}

為此我得到

$ g++ -o answer answer.cpp -lfmt; ./answer 
2023-01-02T16:26:17.009359309
$ 

(下面是基於spdlog的最初的、較早的、略微偏離的推理嘗試。但是spdlog包裝了fmt並覆蓋了它的格式。)

它在格式頁面上,您需要類似%Y-%m-%d %H:%M:%S.%e的內容。 請注意, %e%f%F為您提供毫秒、微秒和納秒。 編輯:盡管那是spdlog格式。

這是一個簡單的示例,為了簡單起見,來自我的 R package RcppSpdlog通過spdlog訪問fmt

> library(RcppSpdlog)
> RcppSpdlog::log_set_pattern("[%Y-%m-%d %H:%M:%S.%f] [%L] %v")
> RcppSpdlog::log_warn("Hello")
[2023-01-02 15:00:49.746031] [W] Hello
> RcppSpdlog::log_set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%L] %v")
> RcppSpdlog::log_warn("World")
[2023-01-02 15:01:02.137] [W] World
> 

請注意所述微秒和毫秒的顯示。

編輯:您的示例還有其他問題。 這是一個簡化的答案,打印幾秒鍾,默認情況下它會小幅下降到納秒(對我來說,在 Linux 上):

$ cat answer.cpp
#include <chrono>
#include <fmt/format.h>
#include <fmt/chrono.h>

int main() {
    fmt::print("{:%S}\n", std::chrono::system_clock::now().time_since_epoch());
    exit(0);
}
$ g++ -o answer answer.cpp -lfmt
$ ./answer 
02.461241690
$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM