bash脚本 - 如何在两个Unix -Timestamp之间获得时间差(小时:分钟:秒)

发布于 2025-01-21 05:01:34 字数 471 浏览 1 评论 0原文

我需要在小时,分钟和几秒钟内获得两个Unix-Timestamps之间的时差。我可以在几分钟和几秒钟内正确获得不同的情况,但是小时总是错的。

我有两个unix-timestamps,我减去有所不同。

1595455100-1595452147 = 2953 (这是同一天2:09:07 pm和2:58:20 pm之间的时间差)

然后我做日期-D @2953 +'%i:%m:%s'

我得到04:49:13,但我希望获得0:49:13

我也尝试了date -d @2953 +'%H:%M:%M: %s'日期-d @2953 +'%t'并获得16:49:13。我还检查了大于一个小时的差异,分钟和几秒钟的差异仍然正确,但小时仍然错误。

我不了解小时格式,也不理解任何帮助。

I need to get the time difference between two unix-timestamps in hour, minute, and seconds. I can get the different in minutes and seconds correctly but the hour is always wrong.

I have two unix-timestamps and I subtract to get the difference.

1595455100 - 1595452147 = 2953
(That's the time difference between 2:09:07pm and 2:58:20pm on the same day)

Then I do date -d @2953 +'%I:%M:%S'

I get 04:49:13 but I expect to get 0:49:13

I'd also tried date -d @2953 +'%H:%M:%S' and date -d @2953 +'%T' and get 16:49:13. I've also checked differences greater than an hour, the difference in minute and seconds is still correct but the hour is still wrong.

I don't understand the Hour format and appreciate any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随波逐流 2025-01-28 05:01:34

错误答案的原因是因为时间戳 @0不是某种绝对的0。这是固定的日期时间:

date -d@0 -u
# Thu Jan 1 00:00:00 UTC 1970

您可以做:

eval echo `date -d @$(($ts1 - $ts2)) -u +'$((%d - 01)) days, %H:%M:%Ss'`
# 0 days, 00:09:20s

只要天数小于31

The reason for wrong answer is because the timestamp @0 is not an absolute 0 of some kind. It is the fixed datetime at:

date -d@0 -u
# Thu Jan 1 00:00:00 UTC 1970

You could do:

eval echo `date -d @$(($ts1 - $ts2)) -u +'$((%d - 01)) days, %H:%M:%Ss'`
# 0 days, 00:09:20s

as long as number of days is less than 31

蓝海 2025-01-28 05:01:34

对于此转换,您不一定需要日期。您可以使用整数数学和printf进行娱乐和利润。

start=1595452147
end=1595455100
s=$((end - start))
time=$(printf %02d:%02d:%02d $((s / 3600)) $((s / 60 % 60)) $((s % 60)))
echo $time

也可能有一种方法可以使用date ,但是以上应该可靠地工作。

You don't necessarily need date for this conversion. You can use integer math and printf for fun and profit.

start=1595452147
end=1595455100
s=$((end - start))
time=$(printf %02d:%02d:%02d $((s / 3600)) $((s / 60 % 60)) $((s % 60)))
echo $time

There may be a way to do it with date too, but the above should work reliably.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文