【问题标题】:Changing datetime format in csv files - Batch Scripting/ Powershell [closed]更改 csv 文件中的日期时间格式 - 批处理脚本/Powershell [关闭]
【发布时间】:2020-08-23 14:43:16
【问题描述】:

Changing datetime format in csv files 此解决方案仅在所有行中的日期值都有值时才有效。 如果传递空值,修改后的脚本要处理什么? 此外,解决方案是如果第三个字段是日期格式。 如果我有第 4 个和第 5 个字段作为日期,我也必须更改它们。

【问题讨论】:

  • 使用DateTime.TryParse() 来尝试解析日期。如果值为null,则不能解析为日期。
  • 你的 csv 文件有列标题吗? any 字段是否可以包含需要转换的日期?请显示此类 csv 文件的前 3 或 4 行。不是评论,而是编辑您的问题并将其粘贴到那里。

标签: powershell csv batch-file datetime-format


【解决方案1】:

如果您的 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-13
    • 2015-02-28
    • 1970-01-01
    • 2010-11-14
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多