I haven't been able to find another question - but I feel like there is one out there, so sorry if I'm asking a duplicate question!
I have a date time column in the following format (character):
date <- "02OCT2019:15:04:34.000000"
I've tried to convert the column to a date with
new_date <- as.POSIXct(date, "%d%b%Y:%H:%M:%S%OS")
But it doesn't seem to work. I feel like my problem lies in the month part because it's written in caps. I tried substringing just the date (%d%b%Y) and using as.POSIXct on that, getting the same error.
I don't know if it's relevant, but my locale is
Sys.getlocale()
[1]"LC_COLLATE=Danish_Denmark.1252;LC_CTYPE=Danish_Denmark.1252;LC_MONETARY=Danish_Denmark.1252;LC_NUMERIC=C;LC_TIME=Danish_Denmark.1252"
And the month format used is not Danish, but English (hence OCT, in Danish it would be OKT).
Hope some of you can help me out!
CodePudding user response:
As Ritchie said in the comments. Naming the format does the trick. Furthermore you should change %S%OS
to %OS
. %OS
already does the seconds and fraction, so %S
is not needed.
All in all, the following should work new_date <- as.POSIXct(date, format = "%d%b%Y:%H:%M:%OS")
Edit: This works for me with the following locale:
> Sys.getlocale()
[1] "LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=sv_SE.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=sv_SE.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=sv_SE.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=sv_SE.UTF-8;LC_IDENTIFICATION=C"
CodePudding user response:
library(lubridate)
date <- "02OCT2019:15:04:34.000000"
dmy_hms(date)
# [1] "2019-10-02 15:04:34 UTC"