我使用日期+“%T”打印开始和结束时间,结果如下:
10:33:56
10:36:10
我如何计算并打印这两者之间的差值呢?
我想要的是:
2m 14s
我使用日期+“%T”打印开始和结束时间,结果如下:
10:33:56
10:36:10
我如何计算并打印这两者之间的差值呢?
我想要的是:
2m 14s
当前回答
以下是我的做法:
START=$(date +%s);
sleep 1; # Your stuff
END=$(date +%s);
echo $((END-START)) | awk '{print int($1/60)":"int($1%60)}'
非常简单,取开始时的秒数,然后取结束时的秒数,打印出以分钟为单位的差值:秒。
其他回答
另一种选择是使用dateutils (http://www.fresse.org/dateutils/#datediff):)中的datediff
$ datediff 10:33:56 10:36:10
134s
$ datediff 10:33:56 10:36:10 -f%H:%M:%S
0:2:14
$ datediff 10:33:56 10:36:10 -f%0H:%0M:%0S
00:02:14
你也可以用gawk。Mawk 1.3.4也有strftime和mktime,但旧版本的Mawk和nawk没有。
$ TZ=UTC0 awk 'BEGIN{print strftime("%T",mktime("1970 1 1 10 36 10")-mktime("1970 1 1 10 33 56"))}'
00:02:14
或者这里有另一种GNU日期的方法:
$ date -ud@$(($(date -ud'1970-01-01 10:36:10' +%s)-$(date -ud'1970-01-01 10:33:56' +%s))) +%T
00:02:14
下面是一个只使用日期命令功能的解决方案,使用“ago”,而不使用第二个变量来存储完成时间:
#!/bin/bash
# save the current time
start_time=$( date +%s.%N )
# tested program
sleep 1
# the current time after the program has finished
# minus the time when we started, in seconds.nanoseconds
elapsed_time=$( date +%s.%N --date="$start_time seconds ago" )
echo elapsed_time: $elapsed_time
这给:
$ ./time_elapsed.sh
elapsed_time: 1.002257120
使用GNU日期(可靠的Ubuntu 14.04 LTS)概括@nisetama的解决方案:
start=`date`
# <processing code>
stop=`date`
duration=`date -ud@$(($(date -ud"$stop" +%s)-$(date -ud"$start" +%s))) +%T`
echo $start
echo $stop
echo $duration
收益率:
Wed Feb 7 12:31:16 CST 2018
Wed Feb 7 12:32:25 CST 2018
00:01:09
截至目前(GNU coreutils) 7.4,你现在可以使用-d来做算术:
$ date -d -30days
Sat Jun 28 13:36:35 UTC 2014
$ date -d tomorrow
Tue Jul 29 13:40:55 UTC 2014
你可以使用的单位是天、年、月、小时、分钟和秒:
$ date -d tomorrow+2days-10minutes
Thu Jul 31 13:33:02 UTC 2014
以下是我的做法:
START=$(date +%s);
sleep 1; # Your stuff
END=$(date +%s);
echo $((END-START)) | awk '{print int($1/60)":"int($1%60)}'
非常简单,取开始时的秒数,然后取结束时的秒数,打印出以分钟为单位的差值:秒。