我使用日期+“%T”打印开始和结束时间,结果如下:
10:33:56
10:36:10
我如何计算并打印这两者之间的差值呢?
我想要的是:
2m 14s
我使用日期+“%T”打印开始和结束时间,结果如下:
10:33:56
10:36:10
我如何计算并打印这两者之间的差值呢?
我想要的是:
2m 14s
当前回答
GNU单位:
$ units
2411 units, 71 prefixes, 33 nonlinear units
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: s
* 134
/ 0.0074626866
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: min
* 2.2333333
/ 0.44776119
其他回答
另一种选择是使用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
% start=$(date +%s)
% echo "Diff: $(date -d @$(($(date +%s)-$start)) +"%M minutes %S seconds")"
Diff: 00 minutes 11 seconds
使用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
下面是一个只使用日期命令功能的解决方案,使用“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
下面是Daniel Kamil Kozar的回答,表示小时/分钟/秒:
echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"
所以完整的脚本是:
date1=$(date +"%s")
date2=$(date +"%s")
DIFF=$(($date2-$date1))
echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"