user1735120
user1735120

Reputation: 489

Change time of a single cell in CSV using powershell

I have a .CSV file and i need to modify a single cell by changing only the Time format of the last row.

Import-Csv .\logs.csv | select -Last 1

will output the last row

Date       : 2019-07-31 02:15 GMT
ID         : 1252321

I need to modify the time from the date column from GMT to GMT+8 (military format) on the same .csv file.

Expected Result would be

2019-07-31 10:15:00

Upvotes: 1

Views: 266

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

You could potentially do something like the following, which relies on the ConvertTime method in the TimezoneInfo class. I chose W. Australia Standard Time as the UTC+8 time zone. You can choose something more appropriate. The [-1] index grabs the last row of the CSV contents $csv.

$csv = Import-Csv .\logs.csv
$csv[-1].date = Get-Date ([System.TimeZoneInfo]::ConvertTime([datetime]($csv[-1].date),([System.TimeZoneInfo]::FindSystemTimeZoneById('W. Australia Standard Time')))) -Format 'yyyy-MM-dd HH:mm "GMT"+8'
$csv | Export-Csv .\logs.csv -NoType

You can remove the GMT+8 part if you feel it is not necessary. An easier alternative is to just add X number of hours based on your current system's time zone to the selected time. If you are already in GMT, you can just add 8 hours.

Get-Date [datetime]($csv[-1].date).AddHours(8) -Format 'yyyy-MM-dd HH:mm'

Upvotes: 2

Related Questions