Conversion from character to date/time returns NA

大憨熊 提交于 2019-12-02 01:51:09

问题


I often use as.POSIXct to convert characters to POSIXct, but I get NA sometimes and I don't know why. For example:

DATE <- "Fri Apr 10 11:57:47 2015"
DATE_in_posix <- as.POSIXct(DATE, format="%a %b %d %H:%M:%S %Y")

I tried this too:

DATE_in_posix <- as.POSIXct(DATE, format="%a %h %d %H:%M:%S %Y")

But result for both is always:

> DATE_in_posix
[1] NA

Maybe the input for as.POSIXct is too long? And when it's too long what could be the solution?


回答1:


It's probably because "Fri" and "Apr" are not the correct abbreviations in your locale.

Use Sys.setlocale("LC_TIME", locale) to set your R session's locale to one that will correctly interpret English abbreviations. See the Examples section of ?Sys.setlocale for how to specify locale in the above function call.

For example, on my Ubuntu machine it would be:

> Sys.setlocale("LC_TIME", "en_US.UTF-8")
> as.POSIXct("Fri Apr 10 11:57:47 2015", format="%a %b %d %H:%M:%S %Y")
[1] "2015-04-10 11:57:47 CDT"



回答2:


Thanks a lot Henrik!!!

I changed the LC_TIME category like this, now it works

Sys.getlocale(category = "LC_TIME")
[1] "German_Germany.1252"

Sys.setlocale("LC_TIME", "English")
[1] "English_United States.1252"

DATE_in_posix<-as.POSIXct(DATE,format="%a %b %d %H:%M:%S %Y")
> DATE_in_posix
[1] "2015-04-10 11:57:47 CEST"

and strptime now works too of course

DATE_in_posix<-strptime(DATE,format="%a %b %d %H:%M:%S %Y")
> DATE_in_posix
[1] "2015-04-10 11:57:47 CEST"

Thank you so much guys and have a nice weekend!



来源:https://stackoverflow.com/questions/29563613/conversion-from-character-to-date-time-returns-na

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!