我有两个时间字符串; 例如。 “9点11”,并在同一天“17点22分”(格式为HH:MM)。 如何计算在这两者之间分钟的时间差?
标准能否date
库做到这一点?
例:
#!/bin/bash
MPHR=60 # Minutes per hour.
CURRENT=$(date -u -d '2007-09-01 17:30:24' '+%F %T.%N %Z')
TARGET=$(date -u -d'2007-12-25 12:30:00' '+%F %T.%N %Z')
MINUTES=$(( $(diff) / $MPHR ))
是否有此给出HH小时和分钟做的一个简单的方法:毫米
纯的bash溶液:
old=09:11
new=17:22
# feeding variables by using read and splitting with IFS
IFS=: read old_hour old_min <<< "$old"
IFS=: read hour min <<< "$new"
# convert hours to minutes
# the 10# is there to avoid errors with leading zeros
# by telling bash that we use base 10
total_old_minutes=$((10#$old_hour*60 + 10#$old_min))
total_minutes=$((10#$hour*60 + 10#$min))
echo "the difference is $((total_minutes - total_old_minutes)) minutes"
另一种采用溶液date
(用小时/分钟内有效,日期并不重要)
old=09:11
new=17:22
IFS=: read old_hour old_min <<< "$old"
IFS=: read hour min <<< "$new"
# convert the date "1970-01-01 hour:min:00" in seconds from Unix EPOCH time
sec_old=$(date -d "1970-01-01 $old_hour:$old_min:00" +%s)
sec_new=$(date -d "1970-01-01 $hour:$min:00" +%s)
echo "the difference is $(( (sec_new - sec_old) / 60)) minutes"
见http://en.wikipedia.org/wiki/Unix_time
我想转换日期以UNIX时间戳; 你可以减去获得以秒为单位的差异,然后除以60:
#!/bin/bash
MPHR=60 # Minutes per hour.
CURRENT=$(date +%s -d '2007-09-01 17:30:24')
TARGET=$(date +%s -d'2007-12-25 12:30:00')
MINUTES=$(( ($TARGET - $CURRENT) / $MPHR ))
MPHR=60
CURRENT=09:11
TARGET=17:22
echo $(( ( 10#${TARGET:0:2} - 10#${CURRENT:0:2} ) * MPHR + 10#${TARGET:4} - 10#${CURRENT:4} ))
这是我如何做的:
START=$(date +%s);
sleep 1; # Your stuff
END=$(date +%s);
echo $((END-START)) | awk '{printf "%d:%02d:%02d", $1/3600, ($1/60)%60, $1%60}'
很简单,拿的秒数在开始,然后采取的秒数末,并打印在几分钟的区别:秒。
我一直在寻找与秒的解决方案。 这里找到: 如何计算在bash脚本的时间差?
#!/bin/bash
string1="10:33:56"
string2="10:36:10"
StartDate=$(date -u -d "$string1" +"%s")
FinalDate=$(date -u -d "$string2" +"%s")
date -u -d "0 $FinalDate sec - $StartDate sec" +"%H:%M:%S"
在这里,我已经添加秒,吉尔的解决方案:
function countTimeDiff() {
timeA=$1 # 09:59:35
timeB=$2 # 17:32:55
# feeding variables by using read and splitting with IFS
IFS=: read ah am as <<< "$timeA"
IFS=: read bh bm bs <<< "$timeB"
# Convert hours to minutes.
# The 10# is there to avoid errors with leading zeros
# by telling bash that we use base 10
secondsA=$((10#$ah*60*60 + 10#$am*60 + 10#$as))
secondsB=$((10#$bh*60*60 + 10#$bm*60 + 10#$bs))
DIFF_SEC=$((secondsB - secondsA))
echo "The difference is $DIFF_SEC seconds.";
SEC=$(($DIFF_SEC%60))
MIN=$((($DIFF_SEC-$SEC)%3600/60))
HRS=$((($DIFF_SEC-$MIN*60)/3600))
TIME_DIFF="$HRS:$MIN:$SEC";
echo $TIME_DIFF;
}
STARTTIME=$(date +%s)
验证码:
ENDTIME=$(date +%s)
secs=$(($ENDTIME - $STARTTIME))
printf 'Elapsed Time %dh:%dm:%ds\n' $(($secs/3600)) $(($secs%3600/60)) $(($secs%60))
@Dorian
如果你只是想知道一个程序花了多长时间来运行:时间,人,人的时间!
简单的例子:
jonathan@Odin:~$ time sleep 1
real 0m1.001s
user 0m0.000s
sys 0m0.000s
OK,它并没有给结果在几秒钟内,但你可以把它与格式字符串这样做,或者更简单地与POSIX兼容的选项:
jonathan@Odin:~$ time -p sleep 20
real 20.00
user 0.00
sys 0.00