2014-09-21 178 views
3

嗨,我该如何将它转换为保存日期和时间的日期时间类型对象?如何将日期和时间从字符转换为日期时间类型

DateTime="2007-02-01 00:00:00" 

试图

as.Date(DateTime,'%Y-%m-%d %H:%M:%S') 

,但不会返回时间的一部分。无法弄清楚如何尝试strptime和lubridate后。谢谢。

+0

'as.Date'只返回日历日期,因为类'Date'对象只显示为日历日期。 – 2014-09-21 15:00:30

回答

4

由于@Richard Scriven指出,你不应该使用as.Date,因为它不是datetime类。这里有几个不同的方式:

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" 

您不必指定format=as.POSIXctas.POSIXlt当你有%Y-%m-%d %H:%M:%S格式。在其他情况下,例如%m/%d/%Y %H:%M:%S,您通常必须明确指定格式。

+0

我可能是错的。但是,在我看来,OP希望保持日期和时间,因为它们在字符串中。 '2007-02-01 EST可能不是OP所需的,因为它不包含结果中的'00:00:00'。 – jazzurro 2014-09-21 15:32:35

+0

嗯,这是一个公平点。我知道如果你有一个日期时间为'00:00:00',另一个日期时间在'data.frame'中有非零的HMS,那么它会打印0,即'data.frame(x = c( as.POSIXct(DateTime,tz = Sys.timezone()),as.POSIXct(DateTime,tz = Sys.timezone())+ 1))'(使用上面的对象);我会看看是否有办法通过单独的时间戳做到这一点。 – nrussell 2014-09-21 15:44:51

+0

谢谢!似乎在日期时间格式hms不显示,但在DateTime2格式它是。 – santoku 2014-09-21 16:01:21

1

如果您想专门将“2007-02-01 00:00:00”转换为日期类对象,则需要执行此操作。这是基于this question and answer

print.POSIXct <- function(x,...)print(format(x,"%Y-%m-%d %H:%M:%S")) 
x <- "2007-02-01 00:00:00" 
x <- as.POSIXct(x,tz=Sys.timezone()) 
x 
相关问题