简体   繁体   English

为什么转换时区不能与as.POSIXct…一起使用?[R]

[英]why converting time zone not working with as.POSIXct… [R]

I've read this and it says as.POSIXct is always UTC internally. 我读过这个 ,上面写着as.POSIXct在内部始终是UTC。 No wonder I got 难怪我得到了

> time1 = as.POSIXct('2015-10-25 10:15:13 UTC')
> time1
[1] "2015-10-25 10:15:13 EDT"
# missing tz causes coercion (not converting!) to computer's tz. 
# (I'm in EDT Boston and calculating some data in Dubai time)


> time1 = as.POSIXct('2015-10-25 10:15:13 UTC', tz = 'UTC', usetz = T)
> time1
[1] "2015-10-25 10:15:13 UTC"

# not work
> as.POSIXct(time1, tz = 'Asia/Dubai', usetz = T)
[1] "2015-10-25 10:15:13 UTC"

# works but the result is character
> format(time1, tz = 'Asia/Dubai', usetz = T)
[1] "2015-10-25 14:15:13 GST"
> class(format(time1, tz = 'Asia/Dubai', usetz = T))
[1] "character"

I can use format , but it yields character and I can't use it in plotting something vs time. 我可以使用format ,但是它会产生character并且无法在绘制随时间变化的图形时使用。 How can I plot with local time? 如何绘制当地时间?

tried something and this works: 尝试了一些,这有效:

> library(lubridate)
> time1 = as.POSIXct('2015-10-25 10:15:13 UTC', tz = 'UTC', usetz = T)
> time1
[1] "2015-10-25 10:15:13 UTC"
> force_tz(time1 + 3600*4, tz = 'Asia/Dubai')
[1] "2015-10-25 14:15:13 GST"
> class(force_tz(time1 + 3600*4, tz = 'Asia/Dubai'))
[1] "POSIXct" "POSIXt" 

Also doable with Rbase with a lightly longer syntax (thanks @David Arenburg) 也可以用稍长的语法在Rbase中使用(感谢@David Arenburg)

> time1 = as.POSIXct('2015-10-25 10:15:13 UTC', tz = 'UTC', usetz = T)
> time1
[1] "2015-10-25 10:15:13 UTC"
> as.POSIXct(format(time1, tz = 'Asia/Dubai', usetz = T), tz = 'Asia/Dubai', usetz = T)
[1] "2015-10-25 14:15:13 GST"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM