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

前端 未结 12 1574
走了就别回头了
走了就别回头了 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: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

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

    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.

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

    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!

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

    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))"
    
    0 讨论(0)
  • 2021-01-31 17:28
    TZ=utc date +'%s' -d "1970-01-01 00:00:38"
    
    0 讨论(0)
提交回复
热议问题