用PowerShell从字符串00:00:00获取平均值

发布于 2025-01-22 20:03:13 字数 204 浏览 0 评论 0原文

我有一些数据要分析。一个示例是任务持续时间的列表:

$tasks.duration

00:04:44
00:00:00
00:00:05

是否有一种简单的方法可以从此列表中获取不断的持续时间?显然,您不能仅使用诸如Measure-object之类的东西,因为它是带有特殊字符的字符串。

您将如何处理此问题,为什么?

I have some data to analyse. One example is a list of durations of tasks:

$tasks.duration

00:04:44
00:00:00
00:00:05

Is there a simple way to get the avarage duration from this list? Obviously you can't just use something like Measure-Object, because it's a string with special characters.

How would you approach this and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

起风了 2025-01-29 20:03:13

显然,您不能仅使用Menem-Object之类的东西,因为它是带有特殊字符的字符串。

将字符串解析为 [timespan] 值,然后计算每个秒的平均秒数,将结果转回[timespan],然后最终产生正确的格式格式的字符串:

$measurement = $tasks.duration |ForEach-Object {
  # cast string value to [timespan], output TotalSeconds
  ([timespan]$_).TotalSeconds
} |Measure-Object -Average

# Now we can create a new string value based on the average number of seconds
$avgString = [timespan]::FromSeconds($measurement.Average).ToString('hh\:mm\:ss')

在您提供的示例值的情况下,给出:

PS ~> $avgString
00:01:36

Obviously you can't just use something like Measure-Object, because it's a string with special characters.

Parse the strings into [timespan] values, then calculate the average number of seconds in each, turn the result back into a [timespan] and then finally produce a correctly formatted string:

$measurement = $tasks.duration |ForEach-Object {
  # cast string value to [timespan], output TotalSeconds
  ([timespan]$_).TotalSeconds
} |Measure-Object -Average

# Now we can create a new string value based on the average number of seconds
$avgString = [timespan]::FromSeconds($measurement.Average).ToString('hh\:mm\:ss')

Which, with the sample values you've provided, gives:

PS ~> $avgString
00:01:36
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文