计算bash中两个时间戳之间的差异

rpl*_*lee 9 bash date

我想通过减去两个时间戳来找出总系统启动时间。首先,我使用此命令来获取开始时间和结束时间:

sudo journalctl | grep "Logs begin at" | awk '{print $6" "$7" "$12" "$13}'
Run Code Online (Sandbox Code Playgroud)

这让我得到以下输出:

2020-05-21 05:52:47 2020-05-28 19:37:36
Run Code Online (Sandbox Code Playgroud)

(前两个字段为开始时间,后两个字段为结束时间)

现在我想找出开始时间和结束时间之间的差异,最好采用以下格式:

“0 年、0 个月、7 天,HH:MM:SS”

Che*_*ass 9

那这个呢?

#!/usr/bin/env bash
echo "BASH_VERSION:" $BASH_VERSION 

line="2020-05-21 05:52:47;2020-05-28 19:37:36"
IFS=';' read -a dates <<< $line
startDatetime=${dates[0]}
endDatetime=${dates[1]}

echo "| dates -> " ${dates[@]}
echo "|> startDatetime -> ${startDatetime}"
echo "|> endDatetime -> ${endDatetime}"

startTime=$(date -jf "%Y-%m-%d %H:%M:%S" "${startDatetime}" +%s)
endTime=$(date -jf "%Y-%m-%d %H:%M:%S" "${endDatetime}" +%s)
diffSeconds="$(($endTime-$startTime))"

echo "Diff in seconds: $diffSeconds"
# at this point you have the diff in seconds and you can parse it however you want :)

diffTime=$(gdate -d@${diffSeconds} -u +%H:%M:%S) # you'll need `brew install coreutils`
echo "Diff time(H:M:S): $diffTime"
Run Code Online (Sandbox Code Playgroud)

输出:

BASH_VERSION: 5.0.17(1)-release
| dates ->  2020-05-21 05:52:47 2020-05-28 19:37:36
|> startDatetime -> 2020-05-21 05:52:47
|> endDatetime -> 2020-05-28 19:37:36
Diff in seconds: 654289
Diff time(H:M:S): 13:44:49
Run Code Online (Sandbox Code Playgroud)

要安装最新版本,bash我找到了这篇中等帖子

注意:如果这不起作用,date例如,由于某些版本与该功能不兼容,那么这个想法应该非常相似,并且我确信您可以找到适合您当前版本的解决方法。从逻辑上讲,我看到的最简单的解决方案是:

1)将字符串分成两部分:每个日期时间一个。

2nd)将每个 DateTime 从字符串转换为日期。

3rd)在这些日期之间应用差异:使用每个日期的秒数。

4th)有了差异秒,您可以根据需要显示它(年,日,分钟,秒)

  • 其实是我自己想出来的。再次感谢您的剧本! (2认同)

Jes*_*era 5

与 @chemaclass 版本相同,但这次适用于 Ubuntu (16.04 LTS)。

#!/usr/bin/env bash
echo "BASH_VERSION:" $BASH_VERSION 

line="2020-05-21 05:52:47;2020-05-28 19:37:36"
IFS=';' read -a dates <<< $line
startDatetime=${dates[0]}
endDatetime=${dates[1]}

echo "| dates -> " ${dates[@]}
echo "|> startDatetime -> ${startDatetime}"
echo "|> endDatetime -> ${endDatetime}"


startTime=$(date -d "${startDatetime}" +%s)
endTime=$(date -d "${endDatetime}" +%s)
diffSeconds="$(($endTime-$startTime))"

echo "Diff in seconds: $diffSeconds"
# at this point you have the diff in seconds and you can parse it however you want :)

diffTime=$(date -d @${diffSeconds} +"%H:%M:%S" -u)
echo "Diff time(H:M:S): $diffTime"
Run Code Online (Sandbox Code Playgroud)

输出:

BASH_VERSION: 5.0.0(1)-release
| dates ->  2020-05-21 05:52:47 2020-05-28 19:37:36
|> startDatetime -> 2020-05-21 05:52:47
|> endDatetime -> 2020-05-28 19:37:36
Diff in seconds: 654289
Diff time(H:M:S): 13:44:49
Run Code Online (Sandbox Code Playgroud)

我按照本教程将 bash 更新到版本 5.0.0 。使用默认的 bash 版本 (4.4.20) 不起作用。redirection unexpected由于该<<<符号,您将在第 3 行收到类似以下的错误消息: