Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

r - how to convert date and time from character to datetime type

hi how shall i convert this to a datetime type object which preserves both the date and the time?

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

Tried

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

but doesn't returns the time part. couldn't figure out how after trying strptime and lubridate. thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...