我们可以使用内置的printf函数打印当前时间,而无需调用像date这样的外部命令,
We can print the current time with the builtin printf function, without needing to invoke an external command like date, like this:
printf '%(%Y-%m-%d:%H:%M:%S)T %s\n' -1 # sample output: 2019-03-30:17:39:36,846我们如何使printf也可以打印毫秒或纳秒?在格式字符串中使用%3N或%N无效:
How can we make printf to print milliseconds or nanoseconds as well? Using %3N or %N in the format string doesn't work:
printf '%(%Y-%m-%d:%H:%M:%S,%3N)T %s\n' -1 # outputs 2019-03-30:17:38:16,%3N printf '%(%Y-%m-%d:%H:%M:%S,%N)T %s\n' -1 # outputs 2019-03-30:17:38:16,%N但是,date命令可以正常工作:
However, the date command works fine:
date +%Y-%m-%d:%H:%M:%S,%3N # gives 2019-03-30:17:39:36,846 date +%Y-%m-%d:%H:%M:%S,%N # gives 2019-03-30:17:39:36,160643077这是在Red Hat Linux 7.3版上.
This is on a Red Hat Linux version 7.3.
推荐答案在bash 5中,您可以从EPOCHREALTIME获得微秒精度.但是,printf本身无法直接访问它,因此您需要自己提取微秒.
In bash 5, you can get microsecond precision from EPOCHREALTIME. However, printf itself has no way to access that directly, so you need to extract the microseconds yourself.
$ echo $EPOCHREALTIME; printf '%(%F:%T)T.%d\n' "$EPOCHSECONDS" "${EPOCHREALTIME#*.}"; echo $EPOCHREALTIME 1554006709.936990 2019-03-31:00:31:49.937048 1554006709.937083这需要一些时间,但结果似乎准确到大约0.05毫秒.
This takes a little time, but the result appears to be accurate to about 0.05 milliseconds.
更多推荐
内置printf可以打印当前时间(以毫秒或纳秒为单位)
发布评论