I am running some gnu time scripts which generates output of the form mm:ss.mm (minutes, seconds and miliseconds, for example 1:20.66) or hh:MM:ss (hours, minutes and seconds, for example 1:43:38). I want to convert this to seconds (in order to compare them and plot them in a graphic).

Which is the easiest way to do this using bash?

share|improve this question
up vote 4 down vote accepted

Assuming you can run the GNU date command:

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

If the script is generating "mm:ss.mm" you'll need to add "00:" to the beginning, or date will reject it.

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

share|improve this answer
    
Just a note that date will run issues if you're trying to interpret standards like those seen in GTFS, where time can go beyond 23 hours. E.g., 27:05:00 is legitimate. – Liam Jones Sep 14 '15 at 15:54

And if you want pure Bash you can do something like

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

The 10# part is mandatory to specify that the numbers are given in radix 10. Without this, you'd get errors if h, m or s is 08 or 09 (as Bash interprets numbers with a leading 0 in octal).

share|improve this answer
$ TZ=utc date -d '1970-01-01 1:43:38' +%s
6218
share|improve this answer
2  
Or put the timezone in the date string: “date -d '1970-01-01 1:43:38Z' +%s” – Lawrence D'Oliveiro Feb 8 '12 at 7:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.