如何在PowerShell中将CSV指定格式的日期时间列转为[datetime]类型?
如何将CSV中的特定格式日期字符串转换为DateTime类型?
你的代码存在两个关键问题:
- 没有引用CSV行中的
datetime列值,只是试图把格式字符串本身转成DateTime,这显然不对 - 指定的格式字符串
"MM/dd/yyyy HH:mm"和实际日期格式"11/13/2022 4:30:00 PM"不匹配,原格式包含秒数和AM/PM标记,且是12小时制时间
正确的解决方案
使用[datetime]::ParseExact方法,明确指定匹配的格式和文化信息(因为这种MM/dd/yyyy+12小时制的格式是美式日期格式),确保转换准确:
$CSV = Import-Csv "this.csv" $formattedCsv = $CSV | Select-Object *, @{ Name = 'ConvertedDateTime' # 可用新列名,或替换原列 Expression = { # 匹配原日期格式:MM/dd/yyyy h:mm:ss tt [datetime]::ParseExact($_.datetime, "MM/dd/yyyy h:mm:ss tt", [cultureinfo]::GetCultureInfo("en-US")) } }
可选:替换原datetime列
如果想直接替换原有datetime列而非新增列,可这样写:
$CSV = Import-Csv "this.csv" $formattedCsv = $CSV | Select-Object *, @{ Name = 'datetime' Expression = { [datetime]::ParseExact($_.datetime, "MM/dd/yyyy h:mm:ss tt", [cultureinfo]::GetCultureInfo("en-US")) } } -ExcludeProperty datetime
更安全的写法(处理转换失败场景)
如果CSV中存在格式错误的日期字符串,用TryParseExact可避免脚本报错:
$CSV = Import-Csv "this.csv" $formattedCsv = $CSV | Select-Object *, @{ Name = 'ConvertedDateTime' Expression = { $output = $null if ([datetime]::TryParseExact($_.datetime, "MM/dd/yyyy h:mm:ss tt", [cultureinfo]::GetCultureInfo("en-US"), [System.Globalization.DateTimeStyles]::None, [ref]$output)) { $output } else { Write-Warning "无法转换日期:$($_.datetime)" $null # 转换失败时返回null,也可自定义返回值 } } }
内容的提问来源于stack exchange,提问作者iceman
相关产品推荐
相关产品推荐

