linuxbashdatetimeprintf

Printing current time in milliseconds or nanoseconds with printf builtin


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

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

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

This is on a Red Hat Linux version 7.3.


Solution

  • 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
    

    This takes a little time, but the result appears to be accurate to about 0.05 milliseconds.