简体   繁体   English

使用awk计算时差

[英]Calculate time difference using awk

I have the following input.txt file. 我有以下input.txt文件。 I need to calculate the time difference of $2 and $3 and print difference in hours. 我需要计算2美元和3美元的时差,并以小时为单位打印差异。

P1,       2016-05-30 00:11:20,    2016-05-30 04:36:40
P2,       2016-05-30 00:07:20,    2016-05-30 04:32:31

I have the following code, but it looks like the hours is not showing accurate. 我有以下代码,但看起来小时显示不准确。 Please help. 请帮忙。

awk -F, '{gsub(/[-:]/," ",$2);gsub(/[-:]/," ",$3);
          d2=mktime($3);d1=mktime($2);
          print $1","(d2-d1)/3600,"hrs";}' input.txt

I am getting the output like this. 我得到这样的输出。

P1,4.42222 hrs
P2,4.41972 hrs

but it should be showing of a difference 4:25:20 hrs 4:25:11 hrs 但应该在4:25:20小时4:25:11之间显示差异

Thanks in advance 提前致谢

If you want to print a number of seconds in HH:MM:SS syntax, you'll need to do the computation yourself. 如果要以HH:MM:SS语法打印若干秒,则需要自己进行计算。 Using printf will prove useful if you want to print, for example, 4:02:30 instead of 4:2:30. 如果要打印,例如4:02:30而不是4:2:30,则使用printf将非常有用。 For example, 例如,

secs = d2 - d1;
printf "%s, %d:%02d:%02d hrs.\n", $1, int(secs/3600), int(secs/60)%60, secs%60
$ cat tst.awk
BEGIN { FS=",[[:space:]]+"; OFS="," }
function dt2secs(dt) { return mktime(gensub(/[-:]/," ","g",dt)) }
function secs2hms(s) { return sprintf("%d:%02d:%02d hrs",s/(60*60),(s/60)%60,s%60) }
{ print $1, secs2hms(dt2secs($3)-dt2secs($2)) }

$ awk -f tst.awk file
P1,4:25:20 hrs
P2,4:25:11 hrs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM