bash,从午夜开始以毫秒为单位获取当前时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16169515/
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
bash, get current time in milliseconds since midnight
提问by user788171
Is there a way to get the current milliseconds past midnight in bash? And if there is a way to do it entirely in bash, how good or bad is the precision of that timestamp?
有没有办法在 bash 中让当前的毫秒数超过午夜?如果有一种方法可以完全在 bash 中完成,那么该时间戳的精度有多好或多坏?
回答by fedorqui 'SO stop harming'
You can get today's midnight with:
您可以通过以下方式获得今天的午夜:
date -d 'today 00:00:00'
in UNIX stamp:
在 UNIX 戳:
date -d 'today 00:00:00' "+%s"
So if you want to get the difference, do:
因此,如果您想获得差异,请执行以下操作:
midnight=$(date -d 'today 00:00:00' "+%s")
now=$(date "+%s")
diff_mills=$(( ($now - $midnight) * 1000 ))
as %sindicates seconds, we have to *1000to get milliseconds.
如%s指示秒,我们必须*1000获得毫秒。
With %N(nanoseconds):
随着%N(纳秒):
midnight=$(date -d 'today 00:00:00' "+%s.%N")
now=$(date "+%s.%N")
diff_mills=$(echo "( $now - $midnight ) * 1000" | bc)
回答by dribnet
You can also use mod instead of an explicit date difference. So for example, with 1 second resolution:
您还可以使用 mod 而不是明确的日期差异。例如,以 1 秒的分辨率:
millis_since_midnight=$[1000 * ( ( `date "+%s"` - 28800 ) % 86400 )]
Note that 28800 is the PST offset from UTC in seconds. This kludge was useful for me on systems like OSX that have BSD time and thus lack the ability to specify --date 'today 00:00:00'.
请注意,28800 是与 UTC 的 PST 偏移量(以秒为单位)。在像 OSX 这样有 BSD 时间因此缺乏指定--date 'today 00:00:00'.

