且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将日期和时间从字符转换为日期时间类型

更新时间:2022-05-03 22:15:41

As @Richard Scriven指出,你不应该使用 as.Date ,因为它不是一个 datetime 类。以下是几种不同的方法:

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"

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

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.