Linux中是否有shell命令以毫秒为单位获取时间?


当前回答

Nano是10−9,milli是10−3。因此,我们可以使用纳秒的前三个字符来得到毫秒:

date +%s%3N

男人约会:

%N纳秒(000000000..999999999) 1970-01-01 00:00:00 UTC以来的%s秒

来源:服务器故障如何在Bash中以毫秒为单位获得当前Unix时间?

其他回答

当你从4.1版本开始使用GNU AWK时,你可以加载时间库并执行以下操作:

$ awk '@load "time"; BEGIN{printf "%.6f", gettimeofday()}'

这将以秒为单位打印自1970-01-01T00:00:00以来的当前时间,精度为亚秒。

the_time = gettimeofday() Return the time in seconds that has elapsed since 1970-01-01 UTC as a floating-point value. If the time is unavailable on this platform, return -1 and set ERRNO. The returned time should have sub-second precision, but the actual precision may vary based on the platform. If the standard C gettimeofday() system call is available on this platform, then it simply returns the value. Otherwise, if on MS-Windows, it tries to use GetSystemTimeAsFileTime(). source: GNU awk manual

在Linux系统上,标准C函数getimeofday()以微秒精度返回时间。

纯bash解决方案

自bash 5.0(2019年1月7日发布)以来,您可以使用内置变量EPOCHREALTIME,它包含自epoch以来的秒数,包括小数点后精确到微秒(echo $EPOCHREALTIME输出类似1547624774.371210)。通过移除。最后三个地方是毫秒:

要么使用

(( t = ${EPOCHREALTIME/./} / 1000 ))

或者类似的东西

t=${EPOCHREALTIME/./}  # remove the dot (s → µs)
t=${t%???}             # remove the last three digits (µs → ms)

无论哪种方式t都是1547624774371。

Perl可以用于此目的,甚至在AIX这样的特殊平台上也是如此。例子:

#!/usr/bin/perl -w

use strict;
use Time::HiRes qw(gettimeofday);

my ($t_sec, $usec) = gettimeofday ();
my $msec= int ($usec/1000);

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
    localtime ($t_sec);

printf "%04d-%02d-%02d %02d:%02d:%02d %03d\n",
    1900+$year, 1+$mon, $mday, $hour, $min, $sec, $msec;

date +%s%N返回秒数+当前纳秒。

因此,echo $(($(date +%s%N)/1000000))就是您所需要的。

例子:

$ echo $(($(date +%s%N)/1000000))
1535546718115

Date +%s返回自epoch以来的秒数,如果有用的话。

在OS X上,date不支持%N标志,我建议使用Homebrew安装coreutils。这将使您能够访问一个名为gdate的命令,其行为与Linux系统上的date相同。

brew install coreutils

为了获得更“原生”的体验,你可以把这个添加到你的.bash_aliases中:

alias date='gdate'

然后执行

$ date +%s%N