简体   繁体   English

Powershell CSV转换日期格式

[英]Powershell Convert Date format in a CSV

I have a CSV file with the following data 我有一个包含以下数据的CSV文件

"Date","Time","Name","SourceIP","DestinationIP"
"Sep  1","03:55:57","mmt-5","172.16.48.158","22.22.22.22"
"Sep  1","03:55:57","mmt-5","172.16.48.158","22.22.22.22"
"Sep  1","03:55:57","mmt-5","172.16.48.158","22.22.22.22"
"Sep  1","03:55:57","mmt-5","172.16.48.158","22.22.22.22"

I would like to convert the date into something more usable like 09-01-2016 (the year would be the current year). 我想将日期转换为更可用的日期,例如09-01-2016(年份将是当前年份)。 How can I accomplish this? 我该怎么做?

That's easy using the [DateTime] class's ParseExact method. 使用[DateTime]类的ParseExact方法很容易。 You supply the string that is a date, you tell it how the date is formatted, and you provide a culture or provider or something, but I always just use $null . 您提供了一个日期字符串,告诉它日期的格式,并提供了区域性或提供者之类的东西,但我始终只使用$null

[datetime]::ParseExact("Sep  1","MMM  d",$null)

That comes out to: 结果是:

Thursday, September 1, 2016 12:00:00 AM

So you could just do something like: 因此,您可以执行以下操作:

$Array | ForEach{[datetime]::ParseExact($_.Date,"MMM  d",$null)}

And that would convert each entry's Date property to a valid [datetime] object. 这样会将每个条目的Date属性转换为有效的[datetime]对象。 Then you just format it however you want: 然后,您可以根据需要对其进行格式化:

$Array | ForEach{[datetime]::ParseExact($_.Date,"MMM  d",$null).ToString("M-d-yyyy")}

That would output: 将会输出:

9-1-2016

Or for the exact thing you asked for use "MM-dd-yyyy" to get 09-01-2016 . 或者,对于您要求的确切内容,请使用"MM-dd-yyyy"以获得09-01-2016

Edit: Thanks to wOxxOm for educating me about the third parameter's necessity when dealing with non-localized date formats! 编辑:感谢wOxxOm在处理非本地化日期格式时向我介绍了第三个参数的必要性! So, if this needs to be localized for other cultures, you will need to include that last parameter. 因此,如果需要针对其他区域性进行本地化,则需要包括最后一个参数。 That can be done as such: 可以这样做:

$Culture = [cultureinfo]::GetCultureInfoByIetfLanguageTag('en-US')
$Array | ForEach{[datetime]::ParseExact($_.Date,"MMM  d",$Culture).ToString("MM-dd-yyyy")}

Edit2: Ok, to replace your current Date field with this information you could pass the array to the Select command, and create a new Date property on the fly, and discard the original, then pass that to Export-CSV : Edit2:好的,要用此信息替换当前的Date字段,可以将数组传递给Select命令,并动态创建一个新的Date属性,并丢弃原始属性,然后将其传递给Export-CSV

$Array | Select *,@{l='Date';e={[datetime]::ParseExact($_.Date,"MMM  d",$null).ToString("M-d-yyyy")}} -Exclude Date | Export-CSV D-Sample-2.csv -NoType

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

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