Converting Character String to Datetime

天大地大妈咪最大 提交于 2020-01-07 06:17:06

问题


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

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