簡體   English   中英

在R中,如何將類似“ 2013年10月5日星期六20:31:59”的字符串轉換為“ 2013-10-05星期六20:31:59”?

[英]In R, how to convert a string like “Saturday, 5 Oct 2013 20:31:59” to “2013-10-05 Saturday 20:31:59”?

如何將Saturday, 5 Oct 2013 20:31:59 2013-10-05 Saturday 20:31:59的字符串轉換為日期時間格式2013-10-05 Saturday 20:31:59 謝謝。 還是如何從字符串中獲取yearmonthdateday of the weekhourminutesecond值?

從字符串創建時間對象時,需要使用相關的格式規范,例如:

(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"
> 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

使用lubridate包裝。

library(lubridate)
x <- "Saturday, 5 Oct 2013 20:31:59"
dmy_hms(x)
## [1] "2013-10-05 20:31:59 UTC"
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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM