powershell - 在 Powershell 中将字符串从 CSV 转换为 DateTime
问题描述
在处理需要转换为 DateTime 的字符串时,我遇到了最奇怪和最烦人的问题。
我正在从 2 个不同的 CSV 文件中执行完全相同的操作 - 它在第一个文件上完美运行,在第二个文件上不断返回错误。
$userDateOut = Get-Date $sourceLine.Date_OUT -Format "dd/MM/yyyy"
$userDateOut = ($userDateOut -as [datetime]).AddDays(+1)
$userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
在第一个 CSV 中, Date_OUT 只是31/12/2021
示例,而在第二个 CSV 中,它是31/12/2021 0:00:00
.
所以在创建 3 行之前$userDateOut
,我做
$userDateOut = $sourceLine.Date_OUT.SubString(0,10)
这使我最终得到与第一个 CSV 相同类型的变量
PS C:\Windows\system32> $userDateOut = $sourceLine.Date_Out.Substring(0,10)
PS C:\Windows\system32> $userDateOut
31/12/2021
PS C:\Windows\system32> $userDateOut.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
然而,有了这个变量,我得到
PS C:\Windows\system32> $userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
Get-Date : Cannot bind parameter 'Date'. Cannot convert value "31/12/2021" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At line:1 char:25
+ $userDateOut = Get-Date $userDateOut -Format "dd/MM/yyyy"
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Date], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand
而且我不知道为什么...有人可以帮忙吗?
解决方案
-Format
只是转换[datetime]
为[string]
- 它不会以任何方式影响输入字符串的解析。
为此,您需要[datetime]::ParseExact()
:
$dateString = '31/12/2021'
# You can pass multiple accepted formats to ParseExact, this should cover both CSV files
$inputFormats = @(
'dd/MM/yyyy H:mm:ss'
'dd/MM/yyyy'
)
$parsedDatetime = [datetime]::ParseExact($dateString, $inputFormat, $null)
然后,您可以根据Get-Date -Format
需要将其转换回预期的输出格式:
推荐阅读
- java - Dali Java Persistence Tools - 数据库数据类型到 Java 数据类型的映射
- php - 如果登录,Symfony 跳过 API 的 JWT 身份验证
- php - 计算另一个连接表中的行数
- django - 如何使用循环从 Django 中的 html 模板请求
- powershell - 我的 Powershell 脚本不做多线程工作,为什么?
- c# - 在 docker 容器内对字符串进行测试失败
- mysql - 当文件不存在时,Mysql“LOAD DATA LOCAL INFILE”不应该停止执行
- python-3.x - 仅当我重新启动 shell 窗口时更新外部文件中的值才有效
- split - 如何在 forEach 循环中拆分 innerHTML 字符串并从两个子字符串中提取输出
- javascript - Firebase Firestore:如何更新或访问和更新地图、数组、文档、集合中的字段值