1

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])
        }
    }
3
  • try Expression = {[datetime]::ParseExact($_.datetime, "mm/dd/yyyy HH:mm", [cultureinfo]::CurrentCulture)} Commented Nov 17, 2022 at 13:23
  • This won't work because [1] for the month part you need MM (lowercase is for minutes) and [2] the example shows there is only one Hour digit (12-hour clock, so that needs to be h, not HH 24-hour clock) plus [3] it uses AM/PM designator you did not include Commented Nov 17, 2022 at 13:31
  • import-csv this.csv | % { $_.Datetime = [datetime]$_.Datetime; $_ } Commented Nov 17, 2022 at 13:45

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Ah Thank you Theo I appreciate your time.
I get "property datetime already exists". Maybe I don't understand the question.
@js2010 Sorry, forgot about that.. Fixed now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.