Simple way to convert HH:MM:SS (hours:minutes:seco

2020-05-19 04:33发布

What's an easy way to convert 00:20:40.28 (HH:MM:SS) to seconds with a Bash script?

Split seconds can be cut out, it’s not essential.

11条回答
欢心
2楼-- · 2020-05-19 05:23

If you are processing a time from ps, mind you that the format 2-18:01 is also possible for 2 days, 19 hours, 1 minute. In that case you'll want to checkout: Parse ps' "etime" output and convert it into seconds

查看更多
相关推荐>>
3楼-- · 2020-05-19 05:31

This would work even if you don't specify hours or minutes: echo "04:20:40" | sed -E 's/(.*):(.+):(.+)/\1*3600+\2*60+\3/;s/(.+):(.+)/\1*60+\2/' | bc

查看更多
乱世女痞
4楼-- · 2020-05-19 05:34

with the shell,

#!/bin/bash

d="00:20:40.28"
IFS=":"
set -- $d
hr=$(($1*3600))
min=$(($2*60))
sec=${3%.*}
echo "total secs: $((hr+min+sec))"
查看更多
5楼-- · 2020-05-19 05:35

If you don't know what exactly do you have - SS, MM:SS or HH:MM:SS, like after youtube-dl --get-duration, then awk magic could be useful:

echo 12 | awk -F\: '{ for(k=NF;k>0;k--) sum+=($k*(60^(NF-k))); print sum }'
12
echo 35:12 | awk -F\: '{ for(k=NF;k>0;k--) sum+=($k*(60^(NF-k))); print sum }'
2112
echo 1:35:12 | awk -F\: '{ for(k=NF;k>0;k--) sum+=($k*(60^(NF-k))); print sum }'
5712
查看更多
Root(大扎)
6楼-- · 2020-05-19 05:37

With GNU date, you can perform the conversion if the duration is less than 24 hours, by treating it as a time of day on the epoch:

to_seconds() {
    local epoch=$(date --utc -d @0 +%F)
    date --utc -d "$epoch $1" +%s.%09N
}

Running it with the example from the question:

$ to_seconds 00:20:40.29
1240.290000000

Note that --utc, @, %s and %N are all GNU extensions not necessarily supported by other implementations.

查看更多
登录 后发表回答