在bash脚本中减去两个时间戳 [英] Subtracting two timestamps in bash script

查看:70
本文介绍了在bash脚本中减去两个时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中包含一组格式为H:M:S.MS的时间戳,我可以读取和打印所有保存的时间戳,但是当我执行诸如减法之类的算术运算(例如Timestamp2 - Timestamp1)时,它没有给出我的答案是,我没有使用bash脚本编程的经验.

任何建议,建议将不胜感激.

这是我的问题的屏幕截图.

这里是一个例子:

Start Time = 17:53:01.166721
End Time = 17:53:01.369787

End Time - Start Time的预期结果是0:00:0.2030660.203066.

解决方案

如果要使用简单的命令行工具处理日期,则需要将时间戳转换为易于处理的格式,例如epoch-

您可以使用date命令执行此操作,您可以将其包装为如下功能:

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

然后您可以直接减去它们:

echo $(( $(timestamp "${Stime[$i]}") - $(timestamp "${Rtime[$i]}") ))

请注意,由于您不是跟踪日期而是仅跟踪时间,因此例如在开始时间为23:59:59而结束时间为00:00:01时会出错. /p>

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 like Subtract (say Timestamp2 - Timestamp1) it doesn't give me the answer, I do not have experience work with bash script programming.

Any suggestions, recommendations will be much appreciated.

Here is the screen shot of my problem.

Here is an example :

Start Time = 17:53:01.166721
End Time = 17:53:01.369787

The expected result for End Time - Start Time is either 0:00:0.203066 or 0.203066.

解决方案

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 "12:20:45.12345"  ==>  1485105645123450000

Then you can subtract them directly:

echo $(( $(timestamp "${Stime[$i]}") - $(timestamp "${Rtime[$i]}") ))

Note that since you are not keeping track of the day but only of the time, you will have errors when, for example, the start time is 23:59:59 and the end time is 00:00:01.

这篇关于在bash脚本中减去两个时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆