mystart=`date`
....
do something
....
myend=`date`
elapsed=calcdiff($mystart, $myend)
echo elapsed time=$(elapsed +%d:%H:%M:%S)
However the script above does not work.
Further question when the runtime is greater than 31 days does %d above then contain e.g. "35"
or does it contain a value modulo 31 (here: 4) ?
Matthew
> In a shell script I would like to calculate the difference between
> two timestamps.
> It should look like similar to:
>
> mystart=`date`
Try this:
$ mystart=`date +%s`
> ....
> do something
> ....
> myend=`date`
Ditto. If you use the %s parameter, then you will get the diff between
the two calls in seconds. Then you can easily manipulate that.
Vilmos
First, you have to construct timestamps, not dates.
In some cases, date don't have format option %s in some versions.
Then you can get timestamp with gnu awk with systime() or mktime()
function as following:
awk 'BEGIN {print systime()}'
So you code will be following:
start="$(awk 'BEGIN {print systime()})'" # or date +"%s"
do_something
end="$(awk 'BEGIN {print systime()})'" # or date +"%s"
diff="$(awk 'BEGIN {print strftime("%Y %m %d %H %M %S", '$(( ${end} - $
{start} ))')}')"
echo "${diff}"
Regards,
Jakub
First, you have to convert dates to timestamps.
In some date versions, the formatter options %s is missing. Then you
can get timestamps with gnu awk version with date functions.
So your code will be following:
start="$(awk 'BEGIN {print systime()}')"
do_something
end="$(awk 'BEGIN {print systime()}')"
why not taking the date with seconds (date +%s ) and then transform
the seconds diff on days / hours .. ?
GNU date (unix time in seconds):
$ date --date=now +%s
1212330415
rest is a piece of cake
calcdiff is not a standard command. If your system has a calcdiff
command, arguments are usually not enclosed in parentheses or separated
by commas. If you have the GNU date command, you can write:
mystart=$(date +%s)
...
myend=$(date +%s)
elapsed=$((myend - mystart))
echo elapsed time="$elapsed" seconds
>In a shell script I would like to calculate the difference between two timestamps.
>It should look like similar to:
>mystart=`date`
mystart=`date +%s`
>....
>do something
>....
>myend=`date`
myend=`date +%s`
>elapsed=calcdiff($mystart, $myend)
elapsed=$(($myend-$mystart))
hour=$(($elapsed/3600))
minute=$(($elapsed/60-60*$hour))
sec=$(($elapsed-3600*$hour-60*$minute))
echo $hour':'$minute':'$sec
use this code snippet to calculate the difference. I did this back in
05-06
NOW=$(date -d "`lynx -dump http://www.tldp.org/timestamp.txt`" +%s)
TIMESTAMP=$(date -d "`lynx -dump -connect_timeout=20 $url/
timestamp.txt`" +%s)
if [[ "$TIMESTAMP" == "" ]] ; then
continue
fi
TIMEFRAME=$(($NOW - $TIMESTAMP))
## printf "Time frame is: %s\n" "$TIMEFRAME"
if [ "$TIMEFRAME" -gt 1209600 ] ; then
cat messagefile | mail -s "TLDP mirror update request"
$admin_email
echo $url" * "$admin_email $TIMEFRAME >> TLDPreminderlog