[time-nuts] Anyone know a portable way of getting seconds since epoch?

David Kirkby david.kirkby at onetel.net
Tue Oct 13 14:03:14 UTC 2009

I've asked this on comp.unix.shell, but never got a 100% satsifactory
answer. Perhaps someone here might know.

Does anyone know how to get the number of seconds since 1/1/1970 on a
Unix system using the shell - not compiling C code. I can't assume the
computer has perl, python or a C compiler.


  - GNU date has the %s format option which returns the epoch

    - More portably, use awk.

        awk 'BEGIN {srand(); printf("%d\n", srand())}'

      This works because srand() sets its seed value with the
      current epoch time if not given an argument. It also returns
      the previous seed value, so the second call gives the epoch

      Note that this doesn't work with older versions of awk. This
      requires a version supporting the POSIX spec for srand(). For
      example, on Solaris this will not work with /usr/bin/awk, but
      will with nawk or /usr/xpg4/bin/awk.

The problem is, from what I gather, POSIX only says the random number
generator has to be seeded from the time, but not what time. Most awks
use seconds since the epoch, but apparently OpenBSD does not. Someone
has proposed that microseconds since midnight would be better. There
appears to be no standard.

The awk/srand method has worked for me on AIX, HP-UX, Linux, OS X and Solaris.

For the purpose I have for this, leapseconds would be best ignored,
though it is not essential they are.


More information about the time-nuts mailing list