将字符串转换为datetime时获取NA而不是datetime

时间:2022-01-27 15:46:01

5 people voted to close this post, but since it has an answer, the site warns against deleting it altogether.

有5人投票结束这篇文章,但由于它有答案,该网站警告不要完全删除它。

To make this as useful as possible for future readers - if you make a syntax mistake in doing string to date-time conversions, the warnings and errors you get (if any) may not point you to the cause of the problem. Instead, your output gets replaced with NA.

为了使这对未来的读者尽可能有用 - 如果你在执行字符串到日期时转换时出现语法错误,你得到的警告和错误(如果有的话)可能不会指出问题的原因。相反,您的输出将替换为NA。

Here is the original sample code w/ warnings and errors. Sample Dates: 5/20/2017 7:28 and 5/20/2017 2:28:57

这是带有警告和错误的原始示例代码。样本日期:2017年5月20日7:28和5/20/2017 2:28:57

Sample code:

library(lubridate)
ymd_hms('5/20/2017 7:28', tz = "America/New_York")

> Warning message:
All formats failed to parse. No formats found. 

strptime("5/20/2017 7:29:00","%m/%d/%Y %H:%M/%S")

as.Date("5/20/2017 7:29:00")

> Error in charToDate(x) : 
  character string is not in a standard unambiguous format

as.POSIXct('5/20/2017 7:29:00',format="%Y-%m-%dT%H:%M:%OS")

There was a post that suggested the following for others encountering the NA error for other reasons:

由于其他原因,有一篇文章建议以下其他人遇到NA错误:

lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")

lct < - Sys.getlocale(“LC_TIME”); Sys.setlocale(“LC_TIME”,“C”)

In this case: a look at the documentation concerning the formatters of the date string could have avoided this question but at the time the post was made, I did not realize this. The key to solving a problem is understanding what is wrong and looking in the right place for it. A good example of working code that has the formatters set up right is in the accepted answer to this question.

在这种情况下:看看有关日期字符串的格式化程序的文档可以避免这个问题,但在发布帖子时,我没有意识到这一点。解决问题的关键是理解错误并找到合适的位置。格式化设置正确的工作代码的一个很好的例子是这个问题的公认答案。

1 个解决方案

#1


2  

The lubridate solution is my personal favourite. You are making two mistakes when using it, though:

润滑剂解决方案是我个人的最爱。但是在使用它时会犯两个错误:

  1. Using ymd, meaning year-month-day. Instead, use mdy for month-day-year.
  2. 使用ymd,表示年 - 月 - 日。相反,使用mdy作为月 - 日 - 年。

  3. Using hms for hours-minutes-seconds, but not supplying seconds.
  4. 使用hms几小时 - 分钟 - 秒,但不提供秒。

Try

> mdy_hms('5/20/2017 7:28:00', tz = "America/New_York")
[1] "2017-05-20 07:28:00 EDT"

or

> mdy_hm('5/20/2017 7:28', tz = "America/New_York")
[1] "2017-05-20 07:28:00 EDT"

#1


2  

The lubridate solution is my personal favourite. You are making two mistakes when using it, though:

润滑剂解决方案是我个人的最爱。但是在使用它时会犯两个错误:

  1. Using ymd, meaning year-month-day. Instead, use mdy for month-day-year.
  2. 使用ymd,表示年 - 月 - 日。相反,使用mdy作为月 - 日 - 年。

  3. Using hms for hours-minutes-seconds, but not supplying seconds.
  4. 使用hms几小时 - 分钟 - 秒,但不提供秒。

Try

> mdy_hms('5/20/2017 7:28:00', tz = "America/New_York")
[1] "2017-05-20 07:28:00 EDT"

or

> mdy_hm('5/20/2017 7:28', tz = "America/New_York")
[1] "2017-05-20 07:28:00 EDT"