如何在bash中减去两个时间戳及其日期?

Man*_*mar 5 command-line bash

我有两个变量:

A= 04.07.2019 23:29:40 和 B= 05.07.2019 01:15:52,我想使用 bash 执行算术运算 C = A - B。

有人能帮我把它们转换成整数吗?一般来说,日期每次都不同,这就是为什么不能忽略日期。

输出应以秒/分钟为单位。如果可能,采用 HH:MM:SS 格式。

pLu*_*umo 6

您可以使用date转换为时间戳,即秒,减去秒,然后转换回HH:MM:SS.

不幸的是,date不会读取指定的格式,因此我们需要DD.MM.YYYYYYYY-MM-DD.

{
A="04.07.2019 23:29:40"
B="05.07.2019 01:15:52"

# Create a function to change DD.MM.YYYY HH:MM:SS to YYYY-MM-DD HH:MM:SS.
convert_date(){ printf '%s-%s-%s %s' ${1:6:4} ${1:3:2} ${1:0:2} ${1:11:8}; }

# Convert to timestamp
A_TS=$(date -d "$(convert_date "$A")" +%s)
B_TS=$(date -d "$(convert_date "$B")" +%s)

# Subtract
DIFF=$((B_TS-A_TS))

# convert to HH:MM:SS (note, that if it's more than one day, it will be wrong!)
TZ=UTC date -d @$DIFF +%H:%M:%S
}
Run Code Online (Sandbox Code Playgroud)

输出:

01:46:12
Run Code Online (Sandbox Code Playgroud)

使用更通用的函数来减去日期:

01:46:12
Run Code Online (Sandbox Code Playgroud)

用法:

$ A="04.07.2019 23:29:40"
$ B="05.07.2019 01:15:52"
$ diff_dates "$(convert_date "$A")" "$(convert_date "$B")"
01:46:12
Run Code Online (Sandbox Code Playgroud)

或者如果您已经有date-compatible 日期:

$ diff_dates "2019-07-04 23:29:40" "2019-07-05 01:15:52"
01:46:12
$ diff_dates "2019-07-05 01:15:52" "2019-07-04 23:29:40"
-01:46:12
Run Code Online (Sandbox Code Playgroud)