在 unix 中减去两个时间戳的命令 [英] command to Substract two timestamps in unix

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

问题描述

我正在编写一个脚本,它需要计算两个时间戳之间的差异.我已经进行了一些搜索,但到目前为止还没有得到任何线索.

I am writing a script and which requires to calculate the difference between the two timestamps . I have done some search but didn't get a clue so far.

例如说:

time1 = 20160314 10:16:27
time2 = 20160313 15:17:28

从上面我需要得到如下结果:区别是:1天5小时1分1秒"

From the above I need to get result like below: difference is: "1 day 5 hours 1 minute 1 second"

请帮我解决这个问题.

推荐答案

您可能想要使用的命令是 date,但其用法取决于您的操作系统.您已在问题的标签中指定了 ,这对于单一答案来说还不够具体.

The command you likely want to use is date, but its usage depends on your operating system. You've specified unix in the tags on your question, which isn't really specific enough for a single answer.

不过,一般来说,您将通过计算日期之间的秒数来计算日期之间的差异.所以你的方法应该是找出每个日期的unix纪元秒,减去以找出差异,然后以适合你的任何格式打印结果.

In general though, you'll calculate differences between dates by counting the seconds between them. So your method should be to figure out the unix epoch second for each of your dates, subtract to find the difference, and then print the results in whatever format suits you.

在 Linux 中,GNU 日期(来自coreutils")有一个 -d 选项,可以理解许多日期引用.

In Linux, GNU date (from "coreutils") has a -d option that can understand a number of date references.

$ time1="20160314 10:16:27"
$ date -d "$time1" '+%s'
1457964987

您可以像这样计算两个日期之间的秒差:

And you can calculate the difference in seconds between two dates like this:

echo "$(( $(date -d "$time1" '+%s') - $(date -d "$time2" '+%s') ))"

将其转换为您的输出格式是一个简单的除法和余数问题:

Converting that to your output format is a simple matter of division and remainders:

s=$(( $(date -d "$time1" '+%s') - $(date -d "$time2" '+%s') ))

printf "%d day(s) %d hours %d minute %d second\n" \
   $(( s / 86400 )) \
   $(( s % 86400 / 3600 )) \
   $(( s % 3600 / 60 )) \
   $(( s % 60 ))

另一方面,在 FreeBSD 中,-d 选项做了一些完全不同的事情,你会使用 -f-v> 解析和调整日期.例如:

In FreeBSD, on the other hand, the -d option does something completely different, and you'd use -f and -v to parse and adjust a date. For example:

$ time1="20160314 10:16:27"
$ date -j -f '%Y%m%d %T' "$time1" '+%s'
1457964987

找出差异看起来类似于 Linux 方法:

Figuring out the difference looks similar to the Linux method then:

s=$(( $(date -j -f '%Y%m%d %T' "$time1" '+%s') - $(date -j -f '%Y%m%d %T' "$time2" '+%s') ))

然后您可以使用我上面显示的相同 printf 命令来格式化您的输出.

You can then use the same printf command I've shown above to format your output.

我没有关于 date 命令在 Solaris 或其他操作系统中如何工作的详细信息,但是您可以从 shell 中man date 来查看这些命令中的任何一个策略似乎与您运行的任何操作系统兼容.

I don't have details on how the date command works in Solaris or other operating systems, but you can man date from a shell to see if either of these strategies appears to be compatible with whatever operating system you're running.

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

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