Changing datetime format in csv files This solution works only if date value in all rows have a value. What is the modified script to handle if null values are passed ? Also, the solution is if 3rd field is date format. WHat if I have 4th and 5th fields also as dates and I have to change them as well.
-
1Use DateTime.TryParse() to, well, try to parse a date. If the value is null,it can't be parsed as a date.vonPryz– vonPryz2020-05-08 05:46:49 +00:00Commented May 8, 2020 at 5:46
-
Do your csv files have column headers? Can any field have a date you need to convert? Please show the first 3 or 4 lines of such a csv file. Not as comment, but edit your question instead and paste it in there.Theo– Theo2020-05-08 09:34:05 +00:00Commented May 8, 2020 at 9:34
Add a comment
|
1 Answer
If your csv files have proper column headers, then using PowerShell you can do the following to look for any field in the file having a date in MM/dd/yyyy hh:mm:ss tt format and update it with the preferred format dd-MMM-yyyy HH:mm:ss like this:
$sourceFolder = 'X:\Path\to\where\the\csv\files\are'
$testDate = Get-Date # just any DateTime object to use with TryParseExact()
# get the files from the path and loop through
Get-ChildItem -Path $sourceFolder -Filter '*.csv' -File | ForEach-Object {
$csv = Import-Csv -Path $_.FullName
# get the header names from the first row
$headers = $csv[0].PSObject.Properties.Name
# loop through all data rows in the csv. (each row is a PSObject with properties)
foreach($item in $csv) {
# loop through all properties (fields) in the item
foreach($name in $headers) {
# see if this is a date in the expected format
if ([DateTime]::TryParseExact($item.$name, 'MM/dd/yyyy hh:mm:ss tt',[cultureinfo]"en-US", 0, [ref]$testDate)) {
$item.$name = '{0:dd-MMM-yyyy HH:mm:ss}' -f $testDate
}
}
}
# if you like, output on screen
$csv | Format-Table -AutoSize
# output to new CSV file
$out = Join-Path -Path $_.DirectoryName -ChildPath ('{0}-Updated{1}' -f $_.BaseName, $_.Extension)
$csv | Export-Csv -Path $out -NoTypeInformation
}