6

GNU date(1) understands the %N format spec, which outputs nanoseconds, so:

$ date +%H:%m:%S.%N

outputs 19:10:03.725196000

BSD date doesn't understand %N. How can I print the current time with sub-second precision on OS X?

2 Answers2

6

As you said, BSD date doesn't support %N. So the straightforward solution is to download GNU's date and install it to either ~/bin or /usr/local/bin and call that when you need to use %N.

However, I would not advise replacing the version that ships with your Mac with the new one. Most of these coreutil programs are written such that their output can be understood by other programs, not necessarily humans, so reliability in output is a necessity. There might be several scripts in your mac that parse the output of BSD's date and any possible changes introduced by replacing with GNU's might or might not break things.


The simplest way to do this safely on a Mac is to use homebrew and install coreutils.

brew info coreutils
coreutils 8.16
http://www.gnu.org/software/coreutils
...   
==> Caveats
All commands have been installed with the prefix 'g'.

The GNU equivalent will be named gdate and is located in /usr/local/Cellar/coreutils/8.16/bin/. You can also set an alias in your .bashrc or its equivalent as

alias date='gdate'
rm -rf
  • 2,971
1

Use python. It's built into macOS, so you don't need to install additional software!

python -c 'import datetime; print datetime.datetime.now()'

If you want the output to be formatted differently, take a look at https://stackoverflow.com/a/18944849/6358721

Wowfunhappy
  • 7,383
  • even if it might be slightly overkill, if you need precision and compatibility, it's a good choice. – Ajax Jun 13 '23 at 00:06
  • 2
    @Ajax One thing to be careful of—at the time this answer was written, python shipped with macOS. This is no longer the case as of this writing in 2023. – Wowfunhappy Jun 13 '23 at 12:12
  • thanks for the heads up! sounds like I need to do py_exec=python3 ; command -v python3 &>/dev/null || py_exec=python ; $py_exc -c '...' ....yuck :-/ – Ajax Aug 28 '23 at 15:30
  • @Ajax Note that even python3 does not ship with macOS, it comes with the developer tools. – Wowfunhappy Aug 29 '23 at 14:35
  • Ah, thanks for letting me know. Since everyone at my company has developer tools installed, I feel safe using this as my "timestamps for bash": python3 -c "from datetime import datetime; print(datetime.now().strftime('%y-%m-%d.%H-%M-%S.%f'))" – Ajax Dec 13 '23 at 15:33
  • Were I writing a generic utility for public consumption, I'd obviously not make any assumptions, but for my use cases, python3 works. – Ajax Dec 13 '23 at 15:34