The file has the following content.
START Sun 04/17/2022 13:01:44.13
END Sun 04/17/2022 14:41:50.60
I'm trying to find a way to automate how many minutes it took from END
to START
time, I don't care about the seconds, just need to know how many minutes took to run.
In this example it took 100 minutes but I had to calculate manually.
I'd appreciate any feed back.
CodePudding user response:
Assuming that your input file is named file.txt
:
$dates = [datetime[]] ((Get-Content file.txt) -replace '^\w ')
[int] ($dates[1] - $dates[0]).TotalMinutes # -> 100
Your date-time strings are in a format that can be cast to
[datetime]
directly.To extract the date-time string from each line, the first whitespace-separated token must be removed, which the regex-based
-replace
operator can do:-replace '^\w '
matches one or more (\w
, letters, digits or_
) at the start (^
) of the string, followed by one more spaces, matching something likeEND
. Since no replacement string is specified, the matched string is effectively removed.
-replace
can operate on an array as its LHS, in which case the operation is performed on each element; therefore, all lines of the input file can serve as the input at once, as returned byGet-Content
.
Subtracting two
[datetime]
instances yields a[timespan]
instance representing the span of time between the two points of time:- Its
.TotalMinutes
property reports the span in fractional minutes (as a[double]
instance) - Casting that value to
[int]
yields an integral number of minutes, using half-to-even midpoint-rounding.
- Its
CodePudding user response:
New-TimeSpan
and the ParseExact()
or TryParse()
method of from an object instance of DateTime
will help you here.
$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
This will provide an output like the below:
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
Access specifically minutes by doing something similar to the below:
> $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