H:M格式linux ubuntu的总和两次

时间:2018-12-24 12:44:14

标签: date ubuntu time

我陷入了剧本。我有$time1:例如"2:05"$time2"2:30"

是否有任何简单的方法可以将这两个值相加?并得到$time3"4:35",我已经尝试了很多与日期-d的组合,但无法解决。

编辑: 好的,这就是我的解决方法:

EPOCH='jan 1 1970'
sum=0
for i in $var13 $var18
do
sum="$(date -u -d "$EPOCH $i" +%s) + $sum"
done
time9=$(echo $sum|bc) #time in seconds
time10=`date "-d@$time9" -u '+%H:%M'` #total time

2 个答案:

答案 0 :(得分:0)

最简单的方法可能是先将两个持续时间都转换为秒:

use strict;
use warnings;

sub parse_min_sec {
    my ($dur) = @_;
    my ($min, $sec) = $dur =~ /\A (\d+) : (\d+) \z/xa
        or die "$0: can't parse duration: $dur\n";
    return $min * 60 + $sec;
}

sub format_min_sec {
    my ($sec) = @_;
    return sprintf "%d:%02d", int($sec / 60), $sec % 60;
}

my $time1 = "2:05";
my $time2 = "2:30";
my $time3 = format_min_sec(parse_min_sec($time1) + parse_min_sec($time2));
print "Result: $time3\n";

输出:

Result: 4:35

答案 1 :(得分:0)

您可能需要使用Python自定义代码

def split_time(timestr):
    h, m = timestr.split(':')
    return int(h), int(m)

time1 = "2:05"
time2 = "2:30"

t1 = split_time(time1)
t2 = split_time(time2)
m = (t1[1]+t2[1])%60
h = t1[0]+t2[0]+(t1[1]+t2[1])//60
print(f'{h}:{m}')

您还可以将Python函数放入脚本中,然后从bash调用它:

def add_times(tstr1, tstr2):
    t1 = [int(x) for x in tstr1.split(':')]
    t2 = [int(x) for x in tstr2.split(':')]
    m = (t1[1]+t2[1])%60
    h = t1[0]+t2[0]+(t1[1]+t2[1])//60
    return f'{h}:{m}'

您可以使用bash进行相同的操作,但是您需要在bash中执行算术运算,这不是它的优势。参见https://unix.stackexchange.com/questions/183178/how-to-sum-time-using-bash