How do I rewrite some lines in a file with new timestamps

前端 未结 1 555
野的像风
野的像风 2021-01-23 13:15

I have a file that uses several different API versions of an application In V1 of the API there are start and end timestamps in the string that always match the pattern

相关标签:
1条回答
  • 2021-01-23 13:44

    This answer is for PowerShell.

    The timestamps in the urls are Unix Milliseconds.

    To replace the timestamps by adding one day (86400000) to them every day, you could do something like this:

    $file  = 'D:\urls.txt'  # your file goes here
    $lines = Get-Content -Path $file
    for ($i = 0; $i -lt $lines.Count; $i++) {
        if ($lines[$i] -match 'startTimestamp=(\d+)') {
            $newTimeStamp = 'startTimestamp={0}' -f ([int64]$matches[1] + 86400000)
            $lines[$i] = $lines[$i] -replace $matches[0], $newTimeStamp
        }
        if ($lines[$i] -match 'endTimestamp=(\d+)') {
            $newTimeStamp = 'endTimestamp={0}' -f ([int64]$matches[1] + 86400000)
            $lines[$i] = $lines[$i] -replace $matches[0], $newTimeStamp
        }
    }
    
    $lines | Set-Content -Path $file -Force
    

    If you would like to be able to set your own start and end timestamps, you can play around with the following conversion methods:

    To convert a Unix MilliSecond timestamp to datetime object:

    $utcDate = [DateTimeOffset]::FromUnixTimeMilliseconds(1572667141000).UtcDateTime    # gives you the date in UTC
    

    or

    $date = [DateTimeOffset]::FromUnixTimeMilliseconds(1572667141000).LocalDateTime  # gives you the date in Local time
    

    To convert a DateTime object into a Unix millisecond timestamp:

    # example uses the current date
    [DateTime]$origin = [DateTime]::new(1970, 1, 1, 0, 0, 0, 0, 'Utc')
    [TimeSpan]$diff = (Get-Date).ToUniversalTime() - $origin
    $unixTimeStamp  = [int64][Math]::Floor($diff.TotalMilliseconds)  # in MilliSeconds
    

    In your example, the startTimestamp converts to 2019-11-01 04:00:01 and the endTimestamp converts to 2019-11-02 03:59:01 (Utc)
    The difference between the startTimestamp and endTimestamp is 86340000 milliseconds (1 day minus 1 minute)

    0 讨论(0)
提交回复
热议问题