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

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

提交回复
热议问题