在 bash 中将 HH:MM:SS.mm 转换为秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9178032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert HH:MM:SS.mm to seconds in bash
提问by Luixv
I am running some gnu time scripts which generates output of the form mm:ss.mm (minutes, seconds and miliseconds, for example 1:20.66) or hh:MM:ss (hours, minutes and seconds, for example 1:43:38). I want to convert this to seconds (in order to compare them and plot them in a graphic).
我正在运行一些 gnu 时间脚本,这些脚本生成 mm:ss.mm(分钟、秒和毫秒,例如 1:20.66)或 hh:MM:ss(小时、分钟和秒,例如 1:43: 38)。我想将其转换为秒(以便比较它们并将它们绘制在图形中)。
Which is the easiest way to do this using bash?
使用 bash 执行此操作的最简单方法是什么?
采纳答案by mkb
Assuming you can run the GNU datecommand:
假设您可以运行 GNUdate命令:
date +'%s' -d "01:43:38.123"
If the script is generating "mm:ss.mm" you'll need to add "00:" to the beginning, or datewill reject it.
如果脚本生成“mm:ss.mm”,您需要在开头添加“00:”,否则date将拒绝它。
If you're on a BSD system (including Mac OS X), you need to run date -j +'%s' "0143.38"unless you have GNU date installed with MacPorts or Homebrewor something.
如果您使用的是 BSD 系统(包括 Mac OS X),date -j +'%s' "0143.38"除非您使用 MacPorts 或Homebrew或其他东西安装了 GNU date,否则您需要运行。
回答by kev
$ TZ=utc date -d '1970-01-01 1:43:38' +%s
6218
回答by Michael Krelin - hacker
And if you want pure Bash you can do something like
如果你想要纯 Bash,你可以做类似的事情
IFS=: read h m s <<<"${hms%.*}"
seconds=$((10#$s+10#$m*60+10#$h*3600))
The 10#part is mandatory to specify that the numbers are given in radix 10. Without this, you'd get errors if h, mor sis 08or 09(as Bash interprets numbers with a leading 0in octal).
该10#部分必须指定数字以基数 10 给出。没有这个,如果h, mor sis 08or 09(因为 Bash 解释数字以0八进制为前导),您会得到错误。

