1

I have two CSV file with 50 column and more than 10K row. There is a column having date-time value. In some records it is 01/18/2013 18:16:32 and some records is 16/01/2014 17:32.

What I want to convert the column data like this: 01/18/2013 18:16. I want to remove seconds value. I want to do it by PowerShell script.

Sample data:

10/1/2014 13:18
10/1/2014 13:21
15/01/2014  12:03:19
15/01/2014  17:39:27
15/01/2014  18:29:44
17/01/2014  13:33:59

1 Answer 1

1

Since you're not going to convert to a sane date format anyway, you can just do a regex replace of that column:

Import-Csv foo.csv |
  ForEach-Object {
    $_.Date = $_.Date -replace '(\d+:\d+):\d+', '$1'
  } |
  Export-Csv -NoTypeInformation foo-new.csv

You could also go the route of using date parsing, but that's probably a bit slower:

Import-Csv foo.csv |
  ForEach-Object {
    $_.Date = [datetime]::Parse($_.Date).ToString('MM/dd/yyyy HH:mm')
  } |
  Export-Csv -NoTypeInformation foo-new.csv

If you're sure that there are no other timestamps or anything that could look like it elsewhere, you can also just replace everything that looks like it without even parsing as CSV:

$csv = Get-Content foo.csv -ReadCount 0
$csv = $csv -replace '(\d{2}/\d{2}/\d{4} \d{2}:\d{2}):\d{2}', '$1'
$csv | Out-File foo-new.csv
Sign up to request clarification or add additional context in comments.

4 Comments

@Joey: thanks for your reply. I want to go with option two. one question i have is my contain other column as well. It will affect them or not. I have uploaded the sample data in question.
I am getting this error while running second option. Exception calling "Parse" with "1" argument(s): "String was not recognized as a valid DateTime."
That's because the date format in there doesn't match your locale. You have to use ParseExact and specify the format. Note also that your sample data doesn't match the format you gave earlier in the question.
Thanks Joey. I will do parseExact to get the data.

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.