DST 左右的 POSIXct 时间?
我想从 POSIX 日期中减去 1 天,并在 DST 前后的同一时间结束。
例如,当我添加一天时:
> as.POSIXct('2009-03-08 23:00:00.000') + 86400
[1] "2009-03-09 23:00:00 EDT"
但是当我过去时,它会抵消:
> as.POSIXct('2009-03-08 23:00:00.000') - 86400
[1] "2009-03-07 22:00:00 EST"
处理 DST 周围绝对时间差异的最佳方法是什么?通常我通过将时间转换为字符串并单独处理它们来处理这个问题,这样就不会应用夏令时。
I want to subtract 1 day from a POSIX date and end up at the same time around DST.
For example, when I add a day:
> as.POSIXct('2009-03-08 23:00:00.000') + 86400
[1] "2009-03-09 23:00:00 EDT"
But when I go past, it offsets:
> as.POSIXct('2009-03-08 23:00:00.000') - 86400
[1] "2009-03-07 22:00:00 EST"
What's the best way to deal with absolute time differences around DST? Usually I deal with this by converting the times into strings and dealing with them separately so that DST isn't applied.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的代码完全按照您的要求执行,因为您没有要求它添加或减去一天,而是要求它添加或减去24 小时。
2009-03-08 23:00:00 EDT
之前 24 小时(86400 秒) 是2009-03-07 22:00:00 EST
>。我不熟悉 R 库,但熟悉它们包装的 POSIX 函数。如果您采用 POSIXct,请将其day
属性减 1,然后通过POSIXlt
将其“重新转换”为POSIXct
(以确保例如,2 月 -1 日变为 1 月 31 日)那么您应该能够可靠地减去一天。Your code is doing exactly what you asked it to do, because you didn't ask it to add or subtract one day, you asked it to add or subtract 24 hours. 24 hours (86400 seconds) before
2009-03-08 23:00:00 EDT
is2009-03-07 22:00:00 EST
. I'm not familiar with the R libraries, but I am familiar with the POSIX functions that they wrap. If you take a POSIXct, decrease itsday
property by 1, and then "re-cast" it toPOSIXct
viaPOSIXlt
( to ensure that e.g. February -1st becomes January 31st) then you should be able to subtract one day reliably.将日期时间存储为 UTC - 或者在本例中转换为 UTC 减去一天并转换回本地时间。 (这忽略了闰秒)
Store datetimes as UTC - or in this case convert to UTC subtract a day and convert back to local time. (This ignores leap seconds)
谢谢霍布斯!我需要用它做更多的工作,但是从 POSIXlt 中的日槽中减去是可行的:
Thanks hobbs! I need to do a little more work with it, but subtracting from the day slot works in POSIXlt:
如果您只想计算天数,可以使用
trunc
来移动日期:If you just want to count the days, you can use
trunc
to just move the day:lubridate 包提供了两个额外的时间跨度类,它们指定了基础包中有些不清楚的内容。来自手册:
持续时间
持续时间测量两个瞬间之间发生的确切时间量。如果间隔期间发生闰秒、闰年或夏令时 (DST) 变化,这可能会产生与时钟时间相关的意外结果。
周期
周期测量两个瞬间之间发生的时钟时间变化。在存在闰秒、闰年和 DST 变化的情况下,周期可以提供对时钟时间的可靠预测。
The package
lubridate
provides two additional timespan classes that specify what is somewhat unclear in the base package. From tha manual:Durations
Durations measure the exact amount of time that occurs between two instants. This can create unexpected results in relation to clock times if a leap second, leap year, or change in daylight savings time (DST) occurs in the interval.
Periods
Periods measure the change in clock time that occurs between two instants. Periods provide robust predictions of clock time in the presence of leap seconds, leap years, and changes in DST.