Conversion from character to date/time returns NA

2020-04-12 18:35发布

问题:

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!



标签: r posixct