改变csv文件中的日期时间格式这个解决方案只适用于所有行的日期值都有一个值的情况下,如果传递的是空值,修改后的脚本该怎么处理?
如果你的csv文件有合适的列头,那么使用 PowerShell 你可以执行以下操作来查找文件中任何一个日期为的字段 MM/dd/yyyy hh:mm:ss tt
格式,并以首选格式更新 dd-MMM-yyyy HH:mm:ss
像这样。
$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
}