Subtracting two timestamps in bash script

后端 未结 3 1961
粉色の甜心
粉色の甜心 2021-01-11 18:00

I have a file that contains a set of Timestamps in format of H:M:S.MS, I can read and print all of the saved Timestamps but when I do some arithmetic operation

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-11 18:44

    If you want to process the date using simple command line tools, you need to convert the timestamps into some easy-to-deal-with format, like epoch-based.

    You can do this with the date command, which you can wrap in a function like so:

    timestamp() { 
        date '+%s%N' --date="$1"
    }
    # timestamp '2020-01-01 12:20:45.12345' => 1577899245123450000
    

    Then you can subtract them directly:

    echo $(( $(timestamp "$etime") - $(timestamp "$stime") ))
    

    Note that the %N format specifier (nanoseconds) is a GNU extension and is not handled in the default macOS date command. Either (a) brew install coreutils and use gdate in the function above or (b) use this alternative function on macOS (but note it lacks support for sub-second measurements):

    timestamp() {
        local format='%Y-%m-%d %H:%M:%S'     # set to whatever format is used
        date -j -f "$format" "$1" '+%s'
    }
    # timestamp '2020-01-01 12:20:45' => 1577899245
    

提交回复
热议问题