簡體   English   中英

PowerShell 中的日期時間無法轉換我的時間

[英]Datetime in PowerShell can't convert my Time

我正在編寫一個腳本來比較兩組時間值,然后計算一個確切的時間。

我的問題是時間戳的計算。 我從 .csv 文件導入時間。 時間是這樣的:

08:37;
11:47;
12:11;
17:34;
etc.

我為時間做了一個變量,所以我總是從 csv 文件中的正確行獲得正確的時間。 我的目標是計算從一個時間戳到另一個時間戳的時間,如下所示:11:47 - 08:37 = 3:10

如果我在我的 PowerShell 腳本中執行此操作,則會發生錯誤:值“time=12:39”無法轉換為類型“System.DateTime”。 錯誤:“字符串未被識別為日期時間。未知單詞從索引 1 開始”

在這種情況下日期時間錯誤嗎? 我怎樣才能使這項工作?

謝謝你的幫助。

如果這與您之前的問題有關,並且 CSV 實際上看起來像這樣:

name;prename;date;time
Gantz;Mario;09.02.;07:37
Gantz;Mario;09.02.;11:23
Gantz;Mario;09.02.;12:34
Gantz;Mario;09.02.;17:03

那么這應該做

# create two variables to hold the times parsed from the CSV, Initialize to $null
$current, $previous = $null
# load the csv and loop through the records
$result = Import-Csv -Path 'D:\Test\times.csv' -Delimiter ';' | ForEach-Object {
    $current = [datetime]::ParseExact($_.time, 'HH:mm', $null)
    if (!$previous) { $previous = $current }
    # subtracting two DateTime objects results in a TimeStamp
    $elapsed  = $current - $previous
    $previous = $current
    # output the record with column 'elapsed' appended
    $_ | Select-Object *, @{Name = 'elapsed'; Expression = {$elapsed.ToString()}}
}

# output on screen
$result | Format-Table -AutoSize

# output to new CSV file
$result | Export-Csv -Path 'D:\Test\times_and_intervals.csv' -Delimiter ';' -NoTypeInformation

屏幕上的 Output:

name  prename date   time  elapsed 
----  ------- ----   ----  ------- 
Gantz Mario   09.02. 07:37 00:00:00
Gantz Mario   09.02. 11:23 03:46:00
Gantz Mario   09.02. 12:34 01:11:00
Gantz Mario   09.02. 17:03 04:29:00

現在我看到您那里還有一個“日期”列,您也應該在轉換為 [datetime] 時將其包括在內:

# create two variables to hold the times parsed from the CSV, Initialize to $null
$current, $previous = $null
# load the csv and loop through the records
$result = Import-Csv -Path 'D:\Test\times.csv' -Delimiter ';' | ForEach-Object {
    $completeDate = '{0}{1} {2}' -f $_.date, (Get-Date).Year, $_.time
    $current = [datetime]::ParseExact($completeDate, 'dd.MM.yyyy HH:mm', $null)
    if (!$previous) { $previous = $current }
    # subtracting two DateTime objects results in a TimeStamp
    $elapsed  = $current - $previous
    $previous = $current
    # output the record with column 'elapsed' appended
    $_ | Select-Object *, @{Name = 'elapsed'; Expression = {$elapsed.ToString()}}
}

# output on screen
$result | Format-Table -AutoSize

# output to new CSV file
$result | Export-Csv -Path 'D:\Test\times_and_intervals.csv' -Delimiter ';' -NoTypeInformation

您收到錯誤是因為您沒有將要導入的值指定為[datetime]我已經復制了我剛剛指定 2 個時間值並減去它們的錯誤:

$st = "08:37" $et = "11:47" $di = $st - $et 無法將值 "08:37" 轉換為類型 "System.Int32"。 錯誤:“輸入字符串的格式不正確。” 在此處輸入圖像描述

解決方案:指定每個條目的值,如下所示:

[datetime]$starttime = "08:37"
[datetime]$endtime = "11:47"
$diff = $endtime - $starttime

在此處輸入圖像描述

如果您只想要以分鍾為單位的時間等,您可以分別輸入$diff.Minutes

希望這對你有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM