Subtract time in nanoseconds

2

I have a file.txt file with this:

15:31:16.481    15:31:09.215
15:31:09.211    15:31:00.019
15:30:59.593    15:30:53.246
15:31:21.244    15:31:17.646
19:17:51.124    19:17:49.691
19:17:48.296    19:17:36.297
19:17:57.565    19:17:51.449
14:48:50.533    14:48:42.582
14:48:42.570    14:48:38.728
12:45:27.004    12:45:22.237
12:45:22.236    12:42:14.240
12:45:42.714    12:45:32.870
15:58:26.751    15:58:26.239
15:58:38.403    15:58:33.887
15:58:30.917    15:58:29.397
15:58:33.882    15:58:32.816
15:58:29.396    15:58:26.756
10:55:32.163    10:55:20.778
10:55:42.058    10:55:32.169
10:55:20.772    10:55:16.773
17:52:02.032    17:51:58.605
17:51:43.187    17:51:39.680
17:52:04.618    17:52:02.511
12:07:02.026    12:06:56.991
12:07:16.169    12:07:10.354
12:07:07.209    12:07:04.719
12:07:10.352    12:07:07.949
12:07:04.715    12:07:02.029
13:00:54.264    13:00:53.082
13:00:56.317    13:00:54.624
15:30:33.907    15:30:29.830
13:59:21.167    13:59:17.767
13:59:27.393    13:59:27.165
13:59:10.779    13:54:19.891
13:59:25.367    13:59:23.280
10:08:52.352    10:08:49.841
10:08:57.469    10:08:54.683
18:30:18.473    18:30:11.887
16:07:53.879    16:07:49.361
16:07:54.661    16:07:54.378
12:45:23.119    12:45:18.661
12:38:41.466    12:38:28.334
12:38:26.695    12:35:10.114

I need to subtract column 2 minus column 1 and only print the difference of hours, for this I was making this script:

while read t1_1 t2_1; do
  secdiff=$((
    $(date -d "$t2_1" +%s) - $(date -d "$t1_1" +%s)
  ))
  nanosecdiff=$((
    $(date -d "$t2_1" +%N) - $(date -d "$t1_1" +%N)
  ))
  printf "%s %s - %s %s = %d milliseconds\n" $t2_1 $t1_1 $((
    (secdiff * 1000) + (nanosecdiff / 1000000)
  ))
done < file.txt

But I do not manage to have the desired exit, someone corrects me that I am doing wrong ...

    
asked by kdetony 16.10.2018 в 05:01
source

1 answer

2

You do not need to pause the date by parts, you can do it all together:

$ date -d 15:31:16.481 +%s.%N
1539721876.481000000
$ date -d 15:31:09.215 +%s.%N
1539721869.215000000

You could also use bc to perform the calculation (since it allows you to do arbitrary precision operations, unlike Bash) and cut to eliminate decimals. I leave the output in milliseconds because apparently that is your goal:

$ bc <<< '(1539721876.481000000 - 1539721869.215000000) * 1000' | cut -d. -f1
7266

How to implement the above in your existing code I leave it to you.

    
answered by 16.10.2018 в 20:02