[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:
> dt00=$(date +%Y%m%d%H%M%S)
> echo "// __ \$dt00: |${dt00}|"
> 
> ... after some long processing for which seconds would be exact
> enough, then I would like to get the seconds elapsed since dt00, like
> this:
> 
> dt02=$(date +%Y%m%d%H%M%S)
> echo "// __ \$dt02: |${dt02}|"

[...]
>  because bash Arithmetic is 10-based.

You wouldn't expect bash to intuit such a crooky arithmetic as
Gregorian datetime (and then, based on what? The number beginning
with 2023? Sounds kind of exciting).

If you could live with a datetime format which date can understand
(instead of your cobbled-up pseudo numeric monster above), you might
harness date to do the work for you.

To wit

  date -I
  => 2023-12-17

(alternatively, if you want a finer resolution):

  date -Iseconds
  => 2023-12-17T11:48:28+01:00

Now date can "read" those (option -d):

  date -d $(date -Iseconds)
  => Sun Dec 17 11:49:46 CET 2023

With all of this, you can do:

  d1=$(date -Iseconds) ; sleep 5 ; d2=$(date -Iseconds)
  echo "$d1 $d2"
  => 2023-12-17T11:51:43+01:00 2023-12-17T11:51:48+01:0

and now:

  echo $(( $(date -d"$d2" +"%s") - $(date -d"$d1" +"%s") ))
  => 5

... the "%s" format indicator telling date to print "seconds since
1970-01-01". Instead of -Iseconds you can do -Ins. See the date man
page for all the gory details.

Me? I'd keep internal results always as "seconds since 1970-01-01"
and only transform on display.

Cheers
-- 
t

Attachment: signature.asc
Description: PGP signature


Reply to: