[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: difference in seconds between two formatted dates ...



On Sun, Dec 17, 2023 at 10:12:11AM +0000, Albretch Mueller wrote:
> ... after some long processing for which seconds would be exact
> enough, then I would like to get the seconds elapsed since dt00

Are you working in bash, or sh?  It makes a difference here.

Others have already mentioned using "date +%s" (a GNU extension)
to get epoch time, twice, and then subtracting those.  That should
be good enough for most purposes, and it'll work in sh, as long as
you have GNU date.  (This is the *only* way that works in sh, apart
from using the "time" builtin on a function call, and parsing its
output, which I would not recommend.)

Bash offers some alternatives, to avoid having to fork two date(1)
processes, light as those are.  The first is:

    unicorn:~$ printf -v dt00 '%(%s)T' -1
    unicorn:~$ echo "$dt00"
    1702821082

This requires GNU libc(*) and bash 4.2 or higher; as an added bonus, if
you use bash 4.3 or higher, you can omit the -1 argument.

Another poster mentioned EPOCHSECONDS.  This is available in bash 5.0
or higher.  You can grab copies of this twice, and then subtract your
copies.  This has the advantage of working on systems without GNU libc
or GNU date.

Finally, there's the SECONDS variable.  You can use this in two different
ways.  The first way is to treat it like EPOCHSECONDS -- capture copies
of it twice, and subtract them.

The second way is to set it to 0 and the start of your interval, and
then capture its value at the end of your interval.

    SECONDS=0
    sleep 5
    echo "$SECONDS sec elapsed"

This works in every version of bash I've got available, so let's call
it 2.05b or higher just to be safe.  It also works without needing
GNU date or GNU libc.  If you're using bash, this is *the* most portable
option.

(*) It requires GNU libc because bash uses the system's strftime(3)
    for interpretation of the format specifier.  Therefore, %s only
    works on systems where libc has that, which means GNU and BSD are
    good, but typically not legacy Unixes.


Reply to: