问题
I am trying to load a dataset into r and change the type of a column into datetime.
strptime
, as.POSIXct
or as.Date
for different cases should work;
This is my code:
a <- structure(list(DATE = c("01/01/2011 12:00:00", "01/02/2011 12:00:00",
"01/03/2011 12:00:00", "01/04/2011 12:00:00", "01/05/2011 12:00:00",
"01/06/2011 12:00:00"), VAL = c(65.34447917, 65.23983333, 65.03183333,
64.89107292, 64.83333333, 64.848625), id = c("VT1-1", "VT1-1", "VT1-1",
"VT1-1", "VT1-1", "VT1-1")), .Names = c("DATE", "VAL", "id"), row.names = c(NA, -6L),
class = c("tbl_df", "tbl", "data.frame"))
b1 <- as.POSIXct(a$DATE, format = "%m/%d/%y %H:%M:%S")
b2 <- strptime(a$DATE,"%m/%d/%Y %H:%M/%S")
But they just return NA
. It is most probably a typo; but how this can be avoided while dealing with different date-time formats?
回答1:
R> library(anytime)
R> anytime(a$DATE)
[1] "2011-01-01 12:00:00 CST" "2011-01-02 12:00:00 CST" "2011-01-03 12:00:00 CST"
[4] "2011-01-04 12:00:00 CST" "2011-01-05 12:00:00 CST" "2011-01-06 12:00:00 CST"
R>
The anytime package was built to make this easy -- you don't need to supply a format you may get wrong, it simply tries a number of plausible ones. For "reasonable" input, it just works.
来源:https://stackoverflow.com/questions/43008017/converting-character-string-to-datetime