Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - convert time interval string to nr. of seconds

I'm trying to convert strings, describing a time interval, to the corresponding number of seconds.

After some experimenting I figured out that I can use date like this:

soon=$(date -d '5 minutes 10 seconds' +%s); now=$(date +%s)
echo $(( $soon-$now ))

but I think there should be an easier way to convert strings like "5 minutes 10 seconds" to the corresponding number of seconds, in this example 310. Is there a way to do this in one command?

Note: although portability would be useful, it isn't my top priority.

like image 598
Pascal Sommer Avatar asked Dec 02 '25 13:12

Pascal Sommer


2 Answers

You could start at epoch

date -d"1970-01-01 00:00:00 UTC 5 minutes 10 seconds" "+%s"
310

You could also easily sub in times

Time="1 day"
date -d"1970-01-01 00:00:00 UTC $Time" "+%s"
86400
like image 111
123 Avatar answered Dec 05 '25 11:12

123


There is one way to do it, without using date command in pure bash (for portability)

Assuming you just have an input string to convert "5 minutes 10 seconds" in a bash variable with a : de-limiter as below.

$ convertString="00:05:10"
$ IFS=: read -r hour minute second <<< "$convertString"
$ secondsValue=$(((hour * 60 + minute) * 60 + second))
$ printf "%s\n" "$secondsValue"
310

You can run the above commands directly on the command-line without the $ mark.

like image 39
Inian Avatar answered Dec 05 '25 11:12

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!