简体   繁体   English

R 使用 as.Date() 转换带有 BST/GMT 标签的 POSIXct 日期

[英]R converting POSIXct dates with BST/GMT tags using as.Date()

I need to use as.Date on the index of a zoo object.我需要在动物园对象的索引上使用 as.Date。 Some of the dates are in BST and so when converting I lose a day on (only) these entries.一些日期在 BST 中,因此在转换时,我(仅)在这些条目上损失了一天。 I don't care about one hour's difference or even the time part of the date at all, I just want to make sure that the dates displayed stay the same.我根本不关心一小时的差异,甚至不关心日期的时间部分,我只想确保显示的日期保持不变。 I'm guessing this is not very hard but I can't manage it.我猜这不是很难,但我无法做到。 Can somebody help please?有人可以帮忙吗?

class(xtsRet)
#[1] "xts" "zoo"

index(xtsRet)
#[1] "2007-07-31 BST" "2007-08-31 BST" "2007-09-30 BST" "2007-10-31 GMT"

class(index(xtsRet))
#[1] "POSIXt"  "POSIXct"

index(xtsRet) <- as.Date(index(xtsRet))

index(xtsRet)
#[1] "2007-07-30" "2007-08-30" "2007-09-29" "2007-10-31"

Minimally reproducible example (not requiring zoo package):最小可重复的示例(不需要zoo包):

my_date <- as.POSIXct("2007-04-01") # Users in non-UK timezone will need to
                                    # do as.POSIXct("2007-04-01", "Europe/London")
my_date
#[1] "2017-04-01 BST"

as.Date(my_date)
#[1] "2017-03-31"

Suppose we have this sample data:假设我们有这个样本数据:

library(zoo)
x <- as.POSIXct("2000-01-01", tz = "GMT")

Then see if any of these are what you want:然后看看这些是否是你想要的:

# use current time zone
as.Date(as.character(x, tz = ""))

# use GMT
as.Date(as.character(x, tz = "GMT"))

# set entire session to GMT
Sys.setenv(TZ = "GMT")
as.Date(x)

Also try "BST" in place of "GMT" and note the article on dates and times in R News 4/1 .还可以尝试用"BST"代替"GMT"并注意R News 4/1 中有关日期和时间的文章。

You can offset the POSIX objects so its not based around midnight.您可以偏移POSIX对象,使其不基于午夜。 1 hour (3600 secs) should be sufficient: 1 小时(3600 秒)应该足够了:

d <- as.POSIXct(c("2007-07-31","2007-08-31","2007-09-30","2007-10-31"))
d
[1] "2007-07-31 BST" "2007-08-31 BST" "2007-09-30 BST" "2007-10-31 GMT"

as.Date(d)
[1] "2007-07-30" "2007-08-30" "2007-09-29" "2007-10-31"
as.Date(d+3600)
[1] "2007-07-31" "2007-08-31" "2007-09-30" "2007-10-31"

I would suggest using as.POSIXlt to convert to a date object, wrapped in as.Date:我建议使用 as.POSIXlt 转换为日期对象,包装在 as.Date 中:

d <- as.POSIXct(c("2007-07-31","2007-08-31","2007-09-30","2007-10-31"))

d
[1] "2007-07-31 BST" "2007-08-31 BST" "2007-09-30 BST" "2007-10-31 GMT"

as.Date(as.POSIXlt(d))
[1] "2007-07-31" "2007-08-31" "2007-09-30" "2007-10-31"

Achieves the same thing as the +3600 above, but slightly less of a hack实现与上面的 +3600 相同的东西,但稍微少一些黑客攻击

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

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