如何将日期和时间从字符转换为日期时间类型 [英] 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"
尝试
as.Date(DateTime,'%Y-%m-%d %H:%M:%S')
但不返回时间部分。无法弄清楚在尝试strptime和lubridate之后。谢谢。
but doesn't returns the time part. couldn't figure out how after trying strptime and lubridate. thanks.
推荐答案
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.
这篇关于如何将日期和时间从字符转换为日期时间类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!