从 bash 脚本获取十六进制时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3712686/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:38:13  来源:igfitidea点击:

Get hex time stamp from bash script

bashtime

提问by John

I would like to convert the current date and time into a hex time stamp, something like:

我想将当前日期和时间转换为十六进制时间戳,例如:

Tue Feb 2 10:27:46 GMT 2010 converted into 0x6d054a874449e

2010 年 2 月 2 日星期二 10:27:46 GMT 转换为 0x6d054a874449e

I would like to do this from a bash script, any idea how I might do that?

我想从 bash 脚本中执行此操作,知道如何执行此操作吗?

Thanks J

谢谢 J

回答by mob

printf '0x%x' $(date +%s)

回答by Matthew Slattery

Without knowing the unit or epoch for your hex timestamp, it's hard to say for sure (and I was slightly confused by your example of "Feb 2" which is not even close to the current date!).

在不知道十六进制时间戳的单位或纪元的情况下,很难确定(而且我对您的“2 月 2 日”示例感到有些困惑,它甚至不接近当前日期!)。

date +%swill convert the current date into a time_t, the number of seconds since the usual Unix epoch (which is midnight on 1st Jan 1970).

date +%s将当前日期转换为time_t自通常的 Unix 纪元(即 1970 年 1 月 1 日午夜)以来的秒数。

printf "0x%x" some_numberwill convert a value from decimal to hex.

printf "0x%x" some_number将一个值从十进制转换为十六进制。

If you need to convert to a different epoch / unit, you will need to do some calculation. You can do arithmetic in bashusing $(( expression )):

如果您需要转换为不同的纪元/单位,则需要进行一些计算。您可以bash使用$(( expression ))以下方法进行算术运算:

$ time_t=$(date +%s)
$ echo $(($time_t * 1000))
1284505668000

If you want to convert an arbitrary date (like your "Feb 2 ..." example), rather than the current one, and are happy to assume that you have the GNU version of date, then you can use the -doption along with the +%soutput format to do the conversion:

如果您想转换任意日期(例如您的“Feb 2 ...”示例),而不是当前日期,并且很高兴假设您拥有 GNU 版本date,那么您可以使用该-d选项和+%s输出格式进行转换:

$ date -d 'Tue Feb 2 10:27:46 GMT 2010' +%s 
1265106466

An example of putting this all together:

将所有这些放在一起的示例:

$ time_t=$(date -d 'Tue Feb 2 10:27:46 GMT 2010' +%s)
$ time_t_ms=$(($time_t * 1000))
$ hexstamp=$(printf "0x%x" $time_t_ms)
$ echo $hexstamp
0x1268e38b4d0

回答by roblogic

Seconds since unix epoch, in hex:

Unix 纪元以来的秒数,以十六进制表示:

 echo "$(date +%s)"|xargs printf "0x%x"
 0x59a8de5b

Milliseconds since the epoch:

自纪元以来的毫秒数:

 echo "$(date +%s%N)/1000000"|bc|xargs printf "0x%x"
 0x15e3ba702bb

Microseconds:

微秒:

echo "$(date +%s%N)/1000"|bc|xargs printf "0x%x"
0x55818f6eea775

Nanoseconds:

纳秒:

echo "$(date +%s%N)"|xargs printf "0x%x"
0x14e0219022e3745c