[英]Calculate time difference for a given dataset
I have a list of down/up times and need to calculate the total down time, per day我有一个停机/停机时间列表,需要计算每天的总停机时间
Here is a snippet of the original dataset:这是原始数据集的片段:
Jan 1 00:09:56 changed state to down
Jan 1 00:10:02 changed state to up
Jan 1 00:10:45 changed state to down
Jan 1 00:10:52 changed state to up
Jan 1 00:11:45 changed state to down
Jan 1 00:11:52 changed state to up
Jan 2 00:14:55 changed state to down
Jan 2 00:15:05 changed state to up
Jan 2 00:15:35 changed state to down
Jan 2 00:16:41 changed state to up
Jan 3 00:05:22 changed state to down
Jan 3 00:05:28 changed state to up
Jan 3 23:59:58 changed state to down
Jan 4 00:00:19 changed state to up
Jan 4 00:49:28 changed state to down
Jan 4 00:49:34 changed state to up
What I'm asking for is an output like this:我要的是这样的 output :
Jan 1: 20 seconds
Jan 2: 76 seconds
Jan 3: 27 seconds
Jan 4: 6 seconds
I've written this script to get the timestamps into epoch time:我编写了这个脚本来获取时间戳到纪元时间:
while read i; do
datetime=$(echo $i | awk '{print $1" "$2" "$3}')
epochtime=$(date -d "$datetime" +\%s)
echo $epochtime
done < ./file
which will give me the data like this:这会给我这样的数据:
1640995796
1640995802
1640995845
1640995852
...
I can't seem to find a way to combine them to a single line so I can use this code (or similar):我似乎找不到将它们组合成一行的方法,因此我可以使用此代码(或类似代码):
for i in $epochtime; do
starttime=$(awk '{print $2}')
endtime=$(awk '{print $1}')
delta=$(( endtime - starttime ))
echo $delta
done
Thanks in advance!提前致谢!
This doesn't produce exactly the expected output and I cant be bothered counting the seconds and up/down indicators to try to figure out the difference between what I thought the requirements are vs what they actually are but it's the right idea for what you're trying to do:这并不能完全产生预期的 output 并且我不会费心计算秒数和上/下指标来试图找出我认为的要求与实际要求之间的区别,但这是你的正确想法重新尝试做:
$ cat tst.awk
{
prevEt = epochtime
date = $1 " " $2
$1 = (index("JanFebMarAprMayJunJulAugSepOctNovDec",$1) + 2) / 3
epochtime = mktime("2022 " gensub(/:/," ","g"), 1)
}
NR%2 == 0 {
delta += (epochtime - prevEt)
if ( date != prevDate ) {
printf "%s: %d seconds\n", prevDate, delta
delta = 0
prevDate = date
}
}
END {
printf "%s: %d seconds\n", prevDate, delta
}
$ awk -f tst.awk file
: 6 seconds
Jan 1: 24 seconds
Jan 2: 72 seconds
Jan 3: 21 seconds
Jan 4: 6 seconds
Original answer:原答案:
This may be what you're trying to do, using GNU awk for time functions:这可能是你想要做的,使用 GNU awk 时间函数:
$ cat tst.awk
{
prevEt = epochtime
$1 = (index("JanFebMarAprMayJunJulAugSepOctNovDec",$1) + 2) / 3
epochtime = mktime("2022 " gensub(/:/," ","g"), 1)
}
NR%2 == 0 {
print prevEt, epochtime, epochtime - prevEt
}
$ awk -f tst.awk file
1640995796 1640995802 6
1640995845 1640995852 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.