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:16

You can convert minutes to hour, seconds, or minutes with bc command.

By example:

How many minutes for 1000 sec ?

$ echo 'obase=60;1000' | bc
02 00

then -> 2 min

How much hour for 375 min ?

$ echo 'obase=60;375'| bc
06 15

then -> 06h15

How days for 56 hours?

$ echo 'obase=24;56' | bc
02 08

then 02 days and 08 hours

bc with obase is extra!

查看更多
贼婆χ
3楼-- · 2020-05-19 05:16

I haven't tested this but, I think this is how you'd split the string. Followed by multiplying by the appropriate amounts for hours and minutes.

mytime=’00:20:40.28′
part1=${mytime%%:*}; rest=${mytime#*:}
part2=${rest%%:*}; rest=${rest#*:}
part3=${rest%%:*};
查看更多
Animai°情兽
4楼-- · 2020-05-19 05:17
echo "40.25" | awk -F: '{ if (NF == 1) {print $NF} else if (NF == 2) {print $1 * 60 + $2} else if (NF==3) {print $1 * 3600 + $2 * 60 + $3} }'
40.25
echo "10:40.25" | awk -F: '{ if (NF == 1) {print $NF} else if (NF == 2) {print $1 * 60 + $2} else if (NF==3) {print $1 * 3600 + $2 * 60 + $3} }'
640.25
echo "20:10:40.25" | awk -F: '{ if (NF == 1) {print $NF} else if (NF == 2) {print $1 * 60 + $2} else if (NF==3) {print $1 * 3600 + $2 * 60 + $3} }'
72640.25
查看更多
Animai°情兽
5楼-- · 2020-05-19 05:17

I have this old shell function (/bin/sh compatible in the sense of POSIX shell, not bash) which does this conversion in integer math (no fractions in the seconds):

tim2sec() {
    mult=1
    arg="$1"
    res=0
    while [ ${#arg} -gt 0 ]; do
        prev="${arg%:*}"
        if [ "$prev" = "$arg" ]; then
            curr="${arg#0}"  # avoid interpreting as octal
            prev=""
        else
            curr="${arg##*:}"
            curr="${curr#0}"  # avoid interpreting as octal
        fi
        curr="${curr%%.*}"  # remove any fractional parts
        res=$((res+curr*mult))
        mult=$((mult*60))
        arg="$prev"
    done
    echo "$res"
}

Outputs:

$ tim2sec 1:23:45.243
5025

It works with SS, MM:SS and HH:MM:SS only :)

查看更多
做自己的国王
6楼-- · 2020-05-19 05:21

Try this:

T='00:20:40.28'
SavedIFS="$IFS"
IFS=":."
Time=($T)
Seconds=$((${Time[0]}*3600 + ${Time[1]}*60 + ${Time[2]})).${Time[3]}
IFS="$SavedIFS"

echo $Seconds

($<string>) splits <string> based on the splitter (IFS).

${<array>[<index>]} returns the element of the <array> at the <index>.

$((<arithmetic expression>)) performs the arithmetic expression.

Hope this helps.

查看更多
可以哭但决不认输i
7楼-- · 2020-05-19 05:23

Try awk. As a bonus, you can keep the split seconds.

echo "00:20:40.25" | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }'
查看更多
登录 后发表回答