As @Richard Scriven pointed out, you shouldn't be using as.Date
because it's not a datetime class. Here are a few different ways:
DateTime <- "2007-02-01 00:00:00"
DateTime2 <- "02/01/2007 00:06:10"
## default format Y-m-d H:M:S
> as.POSIXct(DateTime,tz=Sys.timezone())
[1] "2007-02-01 EST"
> as.POSIXlt(DateTime,tz=Sys.timezone())
[1] "2007-02-01 EST"
##
## specify format m/d/Y H:M:S
> as.POSIXct(DateTime2,format="%m/%d/%Y %H:%M:%S",tz=Sys.timezone())
[1] "2007-02-01 00:06:10 EST"
> as.POSIXlt(DateTime2,format="%m/%d/%Y %H:%M:%S",tz=Sys.timezone())
[1] "2007-02-01 00:06:10 EST"
##
## using lubridate
library(lubridate)
> ymd_hms(DateTime,tz=Sys.timezone())
[1] "2007-02-01 EST"
> mdy_hms(DateTime2,tz=Sys.timezone())
[1] "2007-02-01 00:06:10 EST"
You don't have to specify format=
for as.POSIXct
and as.POSIXlt
when you have the %Y-%m-%d %H:%M:%S
format. In other cases, like %m/%d/%Y %H:%M:%S
, you usually have to specify the format explicitly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…