以微秒为单位的纪元时间比较

时间:2017-01-06 20:40:49

标签: powershell datetime datetime-format epoch

我正试图在PowerShell中围绕Epoch时间。基本上,我有一个CSV,其列的Epoch时间以微秒为单位。我想只抓住“昨天午夜和今天午夜UTC(但不包括今天午夜UTC)”内的记录。

这样的事情会起作用吗?你如何将日期时间转换为微秒?我只看过几秒钟的帖子..

$yesterdayMidnight = (Get-Date -Hour 0 -Minute 0 -Second 0).AddDays(-1)
$todayMidnight = Get-Date -Hour 0 -Minute 0 -Second 0
Import-Csv "Q:\data.csv" | ForEach-Object {
if (($_."Time-UTC-MicroSec" -le $yesterdayMidnight) -and ($_."Time-UTC-MicroSec" -lt $todayMidnight)) {
  # do stuff with records
}

示例文件:

ID1    ID2 ID3 Time-UTC-MicroSec
2080101 26  501032  1483232054547470
2080101 5   501032  1483231158598830
2080101 30  501012  1483230264931800
2080101 28  501032  1483230721849650
2080101 28  501032  1483231194379190

2 个答案:

答案 0 :(得分:2)

我从here获得了转换函数。首先,你只需要除以一百万就可以将微秒转换回秒。

Function get-epochDate ($epochDate) { [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($epochDate))}

$yesterdayMidnight = (get-date -Hour 0 -Minute 0 -Second 0).AddDays(-1)
$todayMidnight = get-date -Hour 0 -Minute 0 -Second 0

Import-CSV "Q:\data.csv" | ForEach-Object {
    $dt = get-epochDate ([Double]($_."Time-UTC-MicroSec" / 1000000))
    if(($dt -ge $yesterdayMidnight) -and ($dt -lt $todayMidnight)) {
        #Do Stuff With Records
    }
}

答案 1 :(得分:0)

要获得正确的csv文件,我使用以下命令进行转换:

$FileIn = "Q:\Test\2017-01\06\SO_41514002.csv"
(gc $FileIn) -replace " +",","|Set-Content .\Test.csv

我的方法是将日期转换为秒的另一种方法

$FileIn = ".\Test.csv"
$unixEpochStart = new-object DateTime 1970,1,1,0,0,0,([DateTimeKind]::Utc)
$UTCNow = [DateTime]::UtcNow
$TodMid = new-object DateTime $UTCNow.Year,$UTCNow.Month,$UTCNow.Day,0,0,0,([DateTimeKind]::Utc)
$YesMid = $TodMid.AddDays(-1)
$TodMidSec = [int]($TodMid - $unixEpochStart).TotalSeconds
$YesMidSec = [int]($YesMid - $unixEpochStart).TotalSeconds

Import-CSV $FileIN | ForEach-Object {
    $dt = [int]($_."Time-UTC-MicroSec" / 1000000)
    "$YesMidSec $dt $TodMidSec"
    if(($dt -ge $yesMidsec) -and ($dt -lt $todMidsec)) {
    "in range"
    }
}

脚本的输出显示秒数刚刚超出范围:

> .\SO_41514002.ps1
1483574400 1483232055 1483660800
1483574400 1483231159 1483660800
1483574400 1483230265 1483660800
1483574400 1483230722 1483660800
1483574400 1483231194 1483660800