[英]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.