用 sprintf 做数学

Doing math with sprintf

当为 GNUplot 创建标签时,从文本文件中读取,我如何从两列中得到 hours:minutes 的差异,每列都包含一个 H:M 时间戳(例如 23.42)。
例如,这会为现有标签创建两列的串联:

myDate(col1,col3)=sprintf("%s-%s",strcol(1),strcol(3))

是否可以修改它来计算日期以得到类似的东西:

 timeDiffLabel(col5,col6)=sprintf(do-some-math-here,strcol(5),strcol(6))

要解析时间,请使用 strptime 函数:

print strptime('%H:%M', '12:34')

这会打印出 45240.0,这是从时间字符串中解析出的秒数。

如果像这样解析两列中的字符串,则可以减去这些值并使用 strftime:

重新格式化结果
timeDiff(c1, c2) = strftime('%k:%M', strptime('%H:%M', strcol(c2)) - strptime('%H:%M', strcol(c1)))
plot 'test.dat' using 0:0:(timeDiff(1,2)) with labels

这在原则上是可行的,但仅适用于积极的差异。如果差异是例如-1,你会得到 23,因为 str*time 函数适用于日期时间。

一个更复杂的解决方案只使用实际格式差异的绝对值,并在结果前添加一个可选的 -

timeDiff(c1, c2) = (diff = strptime('%H:%M', strcol(c2)) - strptime('%H:%M', strcol(c1)), (diff < 0 ? '-' : '').strftime('%k:%M', abs(diff)))
plot 'test.dat' using 0:0:(timeDiff(1,2)) with labels

所以,使用像

这样的测试文件
12:34  23:54
13:45  11:44
2:33   1:11

你得到