Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

powershell convert csv column to datetime

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])
        }
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading