【问题标题】:How to calculate difference in minutes between START and END times in a file using Powershell or cmd如何使用 Powershell 或 cmd 计算文件中开始时间和结束时间之间的分钟差
【发布时间】:2022-12-16 07:10:45
【问题描述】:
该文件具有以下内容。
START Sun 04/17/2022 13:01:44.13
END Sun 04/17/2022 14:41:50.60
我正在尝试找到一种方法来自动化从END 到START 时间花费了多少分钟,我不关心秒数,只需要知道运行需要多少分钟。
在这个例子中,它花了 100 分钟,但我不得不手动计算。
如果有任何反馈,我将不胜感激。
【问题讨论】:
标签:
powershell
date
difference
【解决方案1】:
假设您的输入文件名为file.txt:
$dates = [datetime[]] ((Get-Content file.txt) -replace '^w+ +')
[int] ($dates[1] - $dates[0]).TotalMinutes # -> 100
【解决方案2】:
New-TimeSpan 和 DateTime 的对象实例的 ParseExact() 或 TryParse() 方法将在这里帮助您。
$Start = [datetime]::ParseExact('04/17/2022 13:01:44.13', 'MM/dd/yyyy HH:mm:ss.ff', $null)
$End = [datetime]::ParseExact('04/17/2022 14:41:50.60', 'MM/dd/yyyy HH:mm:ss.ff', $null)
New-TimeSpan -Start $Start -End $End
这将提供如下所示的输出:
Days : 0
Hours : 1
Minutes : 40
Seconds : 6
Milliseconds : 470
Ticks : 60064700000
TotalDays : 0.0695193287037037
TotalHours : 1.66846388888889
TotalMinutes : 100.107833333333
TotalSeconds : 6006.47
TotalMilliseconds : 6006470
通过执行类似于以下的操作来访问特定的会议记录:
> $result = New-TimeSpan -Start $Start -End $End
> $result.TotalMinutes
100.107833333333
# Round up to 2 decimal places
> [Math]::Round($result.TotalMinutes, 2)
100.11
# Round up to 0 decimal places
> [Math]::Round($result.TotalMinutes, 0)
100