简体   繁体   English

使用PowerShell将日期格式转换为CSV

[英]Convert date format in CSV using PowerShell

I have two CSV file with 50 column and more than 10K row. 我有两个CSV文件,其中包含50列和超过10K的行。 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. 在某些记录中是01/18/2013 18:16:32,在某些记录中是16/01/2014 17:32。

What I want to convert the column data like this: 01/18/2013 18:16 . 我想要像这样转换列数据: 01/18/2013 18:16 I want to remove seconds value. 我想删除秒值。 I want to do it by PowerShell script. 我想通过PowerShell脚本来做到这一点。

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

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:

$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM