How to convert HH: MM: SS date to second with bash?

How to convert date HH: MM: SS to second with bash?

Knowing that this is the date that I restored in the file, so I can not take it in a different format.

I have two variables $ DateStart and $ DateEnd, and I need the difference between them.

+6
source share
4 answers
date +%s 

returns the current time in seconds since 1970-01-01 00:00:00 UTC

if you want to get the set time in seconds from 1970-01-01 00:00:00 UTC, for example:

 kent$ date -d"2008-08-08 20:20:20" +%s 1218219620 

to get the difference in seconds, you just get two dates in seconds and do s1-s2

+5
source

Assuming the time in the format HH: MM: SS is in the variable time_hhmmss and the time in seconds must be saved in time_s :

 IFS=: read -rhms <<<"$time_hhmmss" time_s=$(((h * 60 + m) * 60 + s)) 
+2
source

On a Mac, you can convert the date to another date with a combination of the -j and -f options:

 $ date -j -f '%Y-%m-%d %H:%M:%S' "2016-02-22 20:22:14" '+%s' 1456168934 

Where -j suppresses the change of the system clock, -f <fmt> gives the format used for parsing this date, "2016-02-22 20:22:14" is the input date and +<fmt> is the output format.

+2
source

Try using my solution with sed + awk:

 echo $DateStart | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}' echo $DateEnd | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}' 

it breaks the string into sed, then inverts the numbers back ("DD hh mm ss" → "ss mm hh DD") and computes them using awk. It works even after adding days: [[DD-] hh:] mm: ss, for example:

  34:56 12:34:56 123-12:34:56 
0
source

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


All Articles