I've just read about the difference between POSIXlt
and POSIXct
and it is said that POSIXlt is a mixed text and character format like "May, 6 1985", "1990-9-1" or "1/20/2012". When I try such kind of things I get an error
as.POSIXlt("May, 6 1985")
# character string is not in a standard unambiguous format
(How) can we dates with format as quoted above put forward to POSIXlt
? Here are sources saying that such format works (if I get them right): 1, 2.
CodePudding user response:
Read ?strptime
for all the details of specifying a time format. In this case you want %b
(for month name), %d
(day of month), %Y
(4-digit year). (This will only work with an English locale setting as the month names are locale-specific.)
as.POSIXlt("May, 6 1985", format = "%b, %d %Y")
CodePudding user response:
If you have mixed input of formates you can use parse_date_time
from the lubridate
package.
x <- c("May, 6 1985", "1990-9-1", "1/20/2012")
y <- lubridate::parse_date_time(x, c("ymd", "mdy", "dmy"))
str(y)
# POSIXct[1:3], format: "1985-05-06" "1990-09-01" "2012-01-20"
note on c("ymd", "mdy", "dmy")
as this determines the order on first found first converted. Consider 6-1-2000
will encounter mdy
as valid before dmy
so this means it will be first of June and not sixth of January.