[英]How to convert from epoch time to a human readable format in PowerShell?
我正在嘗試將紀元時間轉換為可讀格式。 我有一個文本文件或一個 CSV 文件,其中包含 5 列信息,其中一列包含 Unixtime。 我想獲取導入的文件並將 Unixtime 替換為可讀日期和 output 所有信息到另一個文件。
到目前為止,我在下面的例子中給出了。
數據:
id created state description
-- -------- ------ -----------
12345 1581171592232 pending changes for....
代碼:
$taskarray = @()
Import-Csv c:\tasks.csv | ForEach-Object {$taskarray += $_.created}
foreach($tdate in $taskarray){
$time = [datetimeoffset]::FromUnixTimeMilliseconds($tdate).ToString('yyyy-MM-dd-HH:mm:ss')
$time
}
(([System.DateTimeOffset]::FromUnixTimeSeconds($tdate)).DateTime).ToString("s")
要么
(Get-Date "1970-01-01 00:00:00.000Z") + ([TimeSpan]::FromSeconds($tdate)
首先要注意:您給出的示例的 Unix 時間戳值無效,它應該在 -62135596800 和 253402300799 之間(含)。
第二個備注:Unix 時間戳是 UTC。 我猜你想要 LocalTime 中的返回日期。
我建議為此使用一個小幫手 function:
function ConvertFrom-UnixTimeStamp([Int64]$UnixTimeStamp, [switch]$AsUTC) {
while ($UnixTimeStamp -lt -62135596800 -or $UnixTimeStamp -gt 253402300799) {
# Assume $UnixTimeStamp to include milliseconds
$UnixTimeStamp = [int64][math]::Truncate([double]$UnixTimeStamp / 1000)
}
if ($UnixTimeStamp -gt [Int32]::MaxValue) {
# see: https://en.wikipedia.org/wiki/Year_2038_problem
Write-Warning "The given value exceeds the [Int32]::MaxValue of 2147483647 and therefore enters the Year2038 Unix bug.."
}
# the Unix Epoch is January 1, 1970 midnight in UTC
# older PowerShell versions use:
# [DateTime]$epoch = New-Object System.DateTime 1970, 1, 1, 0, 0, 0, 0, Utc
[DateTime]$epoch = [DateTime]::new(1970, 1, 1, 0, 0, 0, 0, 'Utc')
$date = $epoch.AddSeconds($UnixTimeStamp)
if ($AsUTC) { $date } else { $date.ToLocalTime() }
# or use:
# if ($AsUTC) { [DateTimeOffset]::FromUnixTimeSeconds($UnixTimeStamp).UtcDateTime }
# else { [DateTimeOffset]::FromUnixTimeSeconds($UnixTimeStamp).LocalDateTime }
}
假設您的輸入文件看起來像
id,created,state,description 12345,1598093799,pending,changes for.... 67890,1598093800,pending,changes for.... 74185,1598093801,pending,changes for....
您可以像這樣使用 function:
(Import-Csv -Path 'D:\Test\TheInputFile.csv') |
Select-Object id,
@{Name = 'created'; Expression = {'{0:yyyy-MM-dd-HH:mm:ss}' -f (ConvertFrom-UnixTimeStamp -UnixTimeStamp $_.created)}},
state, description |
Export-Csv -Path 'D:\Test\TheConvertedFile.csv' -NoTypeInformation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.