如何将Saturday, 5 Oct 2013 20:31:59
的字符串转换为日期时间格式2013-10-05 Saturday 20:31:59
?谢谢。或者如何从字符串中获取year
,month
,date
,day of the week
,hour
,minute
,second
值?
答案 0 :(得分:4)
从字符串创建时间对象时,您需要使用相关的格式规范,例如:
(x <- as.POSIXct("Saturday, 5 Oct 2013 20:31:59", format="%A, %d %b %Y %H:%M:%S"))
[1] "2013-10-05 20:31:59 BST"
查看?strftime
以查看格式规范,以及如何提取日期时间的特定部分。
#your desired format
format(x, "%Y-%m-%d %A %H:%M:%S")
[1] "2013-10-05 Saturday 20:31:59"
#only the year
format(x,"%Y")
[1] "2013"
答案 1 :(得分:1)
> now <- Sys.time()
> now
[1] "2014-01-16 16:58:23 IST"
> as.POSIXlt(as.character(now),tz="GMT")
[1] "2014-01-16 17:05:24 GMT"
> str(as.POSIXlt(now))
POSIXlt[1:1], format: "2014-01-16 16:58:23"
> unclass(as.POSIXlt(now))
$sec
[1] 23.1636
$min
[1] 58
$hour
[1] 16
$mday
[1] 16
$mon
[1] 0
$year
[1] 114
$wday
[1] 4
$yday
[1] 15
$isdst
[1] 0
答案 2 :(得分:0)
使用lubridate
包。
library(lubridate)
x <- "Saturday, 5 Oct 2013 20:31:59"
dmy_hms(x)
## [1] "2013-10-05 20:31:59 UTC"
答案 3 :(得分:0)
library(lubridate)
R> date <- now()
R> year(date)
将以下访问者用于其他
Date component Accessor
Year year()
Month month()
Week week()
Day of year yday()
Day of month mday()
Day of week wday()
Hour hour()
Minute minute()
Second second()
Time zone tz()