如何在R中更改此日期的格式

时间:2013-04-05 08:47:09

标签: r

我在R中有这个日期:

> head(mydates)

[1] "2007-01-01" "2007-01-02" "2007-01-03" "2007-01-04" "2007-01-05" "2007-01-08"
> class(mydates)

[1] "Date"

我想把它改成这种格式

> head(targetdates)

[1] "2007-01-01 GMT" "2007-01-02 GMT" "2007-01-03 GMT" "2007-01-04 GMT"
[5] "2007-01-05 GMT" "2007-01-08 GMT"
> class(targetdates)

[1] "POSIXct" "POSIXt"

我怎么能这样做(在R中)?

由于

4 个答案:

答案 0 :(得分:0)

您可以使用as.POSIXlt

R> as.POSIXlt(mydates, tz="GMT")
[1] "2007-01-01 UTC" "2007-01-02 UTC" "2007-01-03 UTC" "2007-01-04 UTC"
[5] "2007-01-05 UTC" "2007-01-08 UTC"

答案 1 :(得分:0)

您可以使用as.POSIXct

mydates
## [1] "2007-01-01" "2007-01-02" "2007-01-03" "2007-01-04" "2007-01-05" "2007-01-08"

class(mydates)
## [1] "Date"

Sys.setenv(TZ = "GMT") #necessary of you want dates to be printed in GMT
as.POSIXct(mydates)
## [1] "2007-01-01 GMT" "2007-01-02 GMT" "2007-01-03 GMT" "2007-01-04 GMT" "2007-01-05 GMT" "2007-01-08 GMT"

另请阅读?POSIXct

答案 2 :(得分:0)

使用lubridate套餐,您可以通过force_tz功能将日期“强制”为GMT:

library(lubridate)

mydate <- as.Date("2007-01-01")
class(mydate)
#[1] "Date"

mydate1 <- as.POSIXlt(mydate) # or use as.POSIXct but you get a datetime format then.
mydate1
#[1] "2007-01-01 UTC"

mydate2 <- force_tz(mydate1, tzone = "GMT")
mydate2
#[1] "2007-01-01 GMT"

class(mydate2)
#[1] "POSIXlt" "POSIXt" 

答案 3 :(得分:0)

试试这个:

> as.POSIXct(format(mydates), tz = "GMT")
[1] "2007-01-01 GMT" "2007-01-02 GMT" "2007-01-03 GMT" "2007-01-04 GMT"
[5] "2007-01-05 GMT" "2007-01-08 GMT"

(有一些问题,为什么你会想要这样做而不只是坚持使用"Date"课程,如果您的数据是每天。)