[英]How to print the current time with fractional seconds, using fmt library
This code这段代码
#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);
Prints this:打印这个:
The time is: 2023-01-02 15:51:23
时间是:2023-01-02 15:51:23
How do I get it to print sub-second precision, for example, milliseconds?如何让它打印亚秒级精度,例如毫秒? Something like:
就像是:
The time is: 2023-01-02 15:51:23.753
时间是:2023-01-02 15:51:23.753
I think you have to do this in two steps -- YMD and HM followed by the high-res seconds.我认为您必须分两步执行此操作——YMD 和 HM,然后是高分辨率秒数。 Here is a worked example, using
fmt
version 9.0 on Ubuntu:这是一个有效的示例,在 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);
}
for which I get为此我得到
$ g++ -o answer answer.cpp -lfmt; ./answer
2023-01-02T16:26:17.009359309
$
(Initial, earlier, slightly off attempt to reason based on spdlog
follows. But spdlog
wraps fmt
and overlays its format.) (下面是基于
spdlog
的最初的、较早的、略微偏离的推理尝试。但是spdlog
包装了fmt
并覆盖了它的格式。)
It is on the format page , you want something like %Y-%m-%d %H:%M:%S.%e
.它在格式页面上,您需要类似
%Y-%m-%d %H:%M:%S.%e
的内容。 Note that %e
, %f
and %F
give you milli, micro and nanoseconds.请注意,
%e
、 %f
和%F
为您提供毫秒、微秒和纳秒。 Edit: That was the spdlog format though.编辑:尽管那是spdlog格式。
Here is a quick example, for simplicity from my R package RcppSpdlog accessing fmt via 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
>
Note the display of micro- and milliseconds as stated.请注意所述微秒和毫秒的显示。
Edit: There is something else going on with your example.编辑:您的示例还有其他问题。 Here is a simplified answer, printing only seconds and it comes by default fractionally down to nanoseconds (for me on Linux):
这是一个简化的答案,只打印几秒钟,默认情况下它会小幅下降到纳秒(对我来说,在 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.