lacrosse1991
lacrosse1991

Reputation: 3162

how should I got about subtracting two different times in a bash environment

I am currently working on a script that processes and combines several different files, and for the one part, it is necessary that I find the difference between two different times in order to determine a "total" amount of time that someone has worked. the times themselves are in the following format

 34:18:00,40:26:00,06:08:00

with the first one being start time, second end time, third total time. Although this one is displayed correctly, there are some entries that need to be double checked and corrected (the total time is not correct based on the start/end time). I have found several different solutions in other posts but most of them also include dates and such too (most of them using awk), I am not experienced with awk so am not sure how to go about removing the date portion from those examples. I have also heard that I could convert the times to unix epoch time, but I was just curious if there were any other ways to accomplish this, thanks!

Upvotes: 1

Views: 111

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46813

Something like this might help you:

#!/bin/bash

time2seconds() {
   a=( ${1//:/ } )
   echo $((${a[0]}*3600+${a[1]}*60+${a[2]}))
}
seconds2time() {
   printf "%.2d:%.2d:%.2d" $(($1/3600)) $((($1/60)%60)) $(($1%60))
}

IFS=, read start stop difference <<< "34:18:00,40:26:00,06:08:00"

printf "Start=%s\n" "$start"
printf "Stop=%s\n" "$stop"
printf "Difference=%s (given in file: %s)\n" $(seconds2time $(($(time2seconds $stop)-$(time2seconds $start)))) "$difference"

Output is:

Start=34:18:00
Stop=40:26:00
Difference=06:08:00 (given in file: 06:08:00)

Note: there's nothing that checks if the times are in a valid format, I don't know how reliable your data are.

Upvotes: 7

Related Questions