Convert HH: MM: SS.mm in seconds to bash

I run some gnu time scripts that generate output of the form mm: ss.mm (minutes, seconds and milliseconds, for example 1: 20.66) or hh: MM: ss (hours, minutes and seconds, for example 1:43:38). I want to convert this to a few seconds (to compare them and draw them on a graph).

What is the easiest way to do this with bash?

+6
source share
3 answers

Assuming you can run the GNU date command:

 date +'%s' -d "01:43:38.123" 

If the script generates "mm: ss.mm", you need to add "00:" to the beginning or date reject it.

If you are on a BSD system (including Mac OS X), you need to run date -j +'%s' "0143.38" unless you have a GNU date set with MacPorts or Homebrew or something like that.

+4
source
 $ TZ=utc date -d '1970-01-01 1:43:38' +%s 6218 
+8
source

And if you want a clean bash, you can do something like

 IFS=: read hms <<<"${hms%.*}" seconds=$((10#$s+10#$m*60+10#$h*3600)) 

Part 10# required to indicate that the numbers are in radix 10. Without this, you will get errors if h , m or s is 08 or 09 (since Bash interprets numbers with leading 0 in octal).

+6
source

Source: https://habr.com/ru/post/907853/


All Articles