如何在R中找到给定日期和时区的夏令时调整?

时间:2012-01-16 12:12:53

标签: php r timezone dst

在PHP(自5.2.0开始)中,我可以编写这段代码:

//$t is timestamp of day I want to look at
$tz=new DateTimeZone('America/New_York');
$transition = $tz->getTransitions($t,$t);
if(!$transition || count($transition)==0)throw new Exception("Bad timezone")
$offset=$transition[0]['offset'];   //This is seconds ahead of GMT.
      //I.e. -14400 in summer, -18000 in winter.
当我发现这个课/成语时,我几乎快乐地哭了;但有没有办法在R中做同样的事情?或者我是否必须采用我以前在PHP中所做的事情,这是我需要考虑的每个时区的夏季开始/结束日期的硬编码?

(顺便说一句,有关PHP代码的更多信息,请参阅:How to tell if a timezone observes daylight saving at any time of the year?

2 个答案:

答案 0 :(得分:3)

您可以构建两个时间对象,相同的日期和时间,一个在所需的时区,另一个在GMT,并查看它们的差异。

# Winter: London uses GMT
> ISOdatetime(2012, 01, 01, 00, 00, 00, "Europe/London") - 
  ISOdatetime(2012, 01, 01, 00, 00, 00, "GMT")
Time difference of 0 secs

# Summer: London uses GMT+1
> ISOdatetime(2012, 08, 01, 00, 00, 00, "Europe/London") - 
  ISOdatetime(2012, 08, 01, 00, 00, 00, "GMT")
Time difference of -1 hours

答案 1 :(得分:3)

使用as.POSIXctas.POSIXlt,您可以获得此信息。例如:

tz = 'Europe/Madrid'
d1 <- as.POSIXct('2010-01-01 12:00:00',  tz = tz)
as.POSIXlt(d1)$isdst ## 0 since it's not DST

如果您需要与UTC的区别:

d0 <- as.POSIXct(format(d1,  tz = 'UTC'),  tz = tz)
as.numeric(d1 - d0) ## 1 hour

另一天也一样:

d2 <- as.POSIXct('2010-07-01 12:00:00',  tz = tz)
as.POSIXlt(d2)$isdst ## 1 since it is DST
d0 <- as.POSIXct(format1(d2,  tz = 'UTC'),  tz = tz)
as.numeric(d2 - d0) ## 2 hour