Subtracting two timestamps in a bash script

I have a file containing a set of timestamps in the format H:M:S.MS , I can read and print all the saved timestamps, but when I perform some arithmetic operation, for example Subtract (for example, Timestamp2 - Timestamp1 ), it does not give the answer is me, I have no experience with programming a bash script.

Any suggestions, recommendations would be highly appreciated.

Here is a screenshot of my problem.

Here is an example:

 Start Time = 17:53:01.166721 End Time = 17:53:01.369787 

The expected result for End Time - Start Time is either 0:00:0.203066 or 0.203066 .

+7
date math bash timestamp shell
source share
3 answers

If you want to process the date using simple command line tools, you need to convert the timestamps into some easy-to-use format, for example, based on eras.

You can do this with the date command, which you can wrap in a function like this:

 timestamp() { date '+%s%N' --date="$1" } # timestamp "12:20:45.12345" ==> 1485105645123450000 

Then you can subtract them directly:

 echo $(( $(timestamp "${Stime[$i]}") - $(timestamp "${Rtime[$i]}") )) 

Please note that since you are not tracking the day, but only the time, you will have errors if, for example, the start time is 23:59:59 and the end time is 00:00:01.

+7
source share

Assuming your variables are integers, you need to apply your calculations in arithmetic estimation to work.

 echo $(( VAR1 - VAR2 )) 

Or, if you want to assign a value:

 VAR3=$(( VAR1 - VAR2 )) 
0
source share

If you need to use bash, you need to convert the timestamp to an integer value:

 $ time="12:34:56.789" $ IFS=":." read -rhms ms <<<"$time" $ echo $h $m $s $ms 12 34 56 789 $ milliseconds=$(( (h*3600 + m*60 + s)*1000 + ms )) $ echo $milliseconds 45296789 

You can then subtract to get a few milliseconds representing diff.

Convert to seconds with some arithmetic and string:

 $ seconds="$((milliseconds / 1000)).$((milliseconds % 1000))" $ echo $seconds 45296.789 

To access the correct gniourf_gniourf point (in an awkward way):

 $ time="12:34:56.7" $ IFS=":." read -rhms ms <<<"$time" $ ms="${ms}000"; ms=${ms:0:3} $ echo $h $m $s $ms 12 34 56 700 # .......^^^ 

Also, strings with invalid octal digits such as "08" and "09" will cause errors in bash arithmetic, so explicitly declare them to be base 10

 milliseconds=$(( (10#$h*3600 + 10#$m*60 + 10#$s)*1000 + 10#$ms )) 
0
source share

All Articles