Simple way to convert HH:MM:SS (hours:minutes:seconds.split seconds) to seconds

前端 未结 12 1573
走了就别回头了
走了就别回头了 2021-01-31 16:40

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.

相关标签:
12条回答
  • 2021-01-31 17:05

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

    echo "00:20:40.25" | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }'
    
    0 讨论(0)
  • 2021-01-31 17:12

    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%%:*};
    
    0 讨论(0)
  • 2021-01-31 17:13

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

    0 讨论(0)
  • 2021-01-31 17:17

    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

    0 讨论(0)
  • 2021-01-31 17:18

    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
    
    0 讨论(0)
  • 2021-01-31 17:19

    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.

    0 讨论(0)
提交回复
热议问题