Linux command-line snippet for absolute timestamps with subsecond resolution in ISO 8601 format
Use
date '+%FT%T.%N'
Sample output:
2024-02-05T22:27:08.064175582
That is sortable output, but a resolution of 1/100 second is probably sufficient. The output can be rounded by postprocessing. For example (properly rounded, not just truncated),
date '+%FT%T.%N' | perl -nle '($secRes, $ns) = split(/\./); $rounded = sprintf("%.2f", $ns / 1000000000); $rounded =~ s/^0//; printf("$secRes$rounded")'
Sample output:
2024-02-05T22:27:08.06
Notes:
- The enclosing single quotes can be left out, but they allow inserting spaces in the output
- It does not work in all cases (in all default shells, for example, Bash, BusyBox, Dash (used, for example, in Debian, LMDE, Ubuntu, and Raspberry Pi), Bourne shell (executable `sh`), and KornShell (executable `ksh`)), but it should work in Bash and Dash.
A sample application
For example, it can be used to get absolute timestamps for start and end of a command (not just the run time in seconds):
clear; echo ; echo "Start time: $(date '+%FT%T.%N' | perl -nle '($secRes, $ns) = split(/\./); $rounded = sprintf("%.2f", $ns / 1000000000); $rounded =~ s/^0//; printf("$secRes$rounded")')" ; echo
git log -i -S"Q10 Max" --all -- keyboards
clear; echo ; echo "End time: $(date '+%FT%T.%N' | perl -nle '($secRes, $ns) = split(/\./); $rounded = sprintf("%.2f", $ns / 1000000000); $rounded =~ s/^0//; printf("$secRes$rounded")')" ; echo
The absolute time may be important later. For example, to know/document when a particular command was run (and how long it took).
References
- Hacker Public Radio episode 4678: High resolution elapsed time in shell scripts. For example, at 12 min 59 secs, near “we can use the date command” in the transcript. Direct download URL (save it with the .ogg filename extension, for example, HPR4678.ogg)
Leave a Reply