Home > Blockchain >  powershell convert csv column to datetime
powershell convert csv column to datetime

Time:11-18

I have a CSV with a 'datetime' column in this format- "11/13/2022 4:30:00 PM". How do I convert that string to a [datetime] type?

I apologize Im having a tough time with this one.

$CSV = Import-Csv "this.csv" 
    
$formattedcsv = $CSV | Select-Object *, @{
        Name        = 'DateTime'
        Expression  = {
            (("MM/dd/yyyy HH:mm") -as [datetime])
        }
    }

CodePudding user response:

The format you show ("11/13/2022 4:30:00 PM") uses the 12-hour clock and has AM/PM designators.

Use this instead:

$dateFormat = 'MM/dd/yyyy h:mm:ss tt'
$formattedcsv = $CSV | 
Select-Object *, 
              @{Name = 'DateTime'
                Expression = {[datetime]::ParseExact($_.datetime, $dateFormat, [cultureinfo]::InvariantCulture)}
              } -ExcludeProperty datetime
  • Related