r - Posixlt 和 Posixct 中的系统日期

标签 r time posix lubridate

我试图使用 Posix 时间的 Sys.Date() 获取昨天的最后一分钟。

force_tz(as.POSIXlt(Sys.Date()-1), tz = 'America/New_York') + 86399
# [1] "2018-01-12 23:59:59 EST" 

正确

force_tz(as.POSIXct(Sys.Date()-1), tz = 'America/New_York') + 86399
# [1] "2018-01-12 15:59:59 EST"

不正确

Sys.Date()
# [1] "2018-01-13"

为什么 as.Posixctas.Posixlt 使用 Sys.Date() 返回两个不同的值,为什么相差 8 小时即使在从 lubridate 应用 force_tz 后?

最佳答案

一如既往,debugonce是你的 friend 。运行debugonce(force_tz) ,您可以看到输出的差异来自于 force_tz 时首先检查分支 is.POSIXct(time) (在这种情况下,应用默认 tzone = "");在 POSIXlt在这种情况下,会命中默认分支,其中 as.POSIXct应用于timetz(time) (对于 UTC 对象,其结果为 POSIXlt)用作时区。

<小时/>

这归结为一些微妙的事情发生;来自?as.POSIXlt.Date :

Dates without times are treated as being at midnight UTC.

因此

tz(as.POSIXlt(Sys.Date()-1))
# [1] "UTC"

但是

tz(as.POSIXct(Sys.Date()-1))
# [1] ""

奇怪的是这不能被覆盖 -- as.POSIXlt.Date不接受tz论据:

formals(as.POSIXlt.Date)
# $x
# $...
<小时/>

如果您想使用POSIXct ,下面这个怎么样?

force_tz(as.POSIXct(sprintf('%s 00:00:00', Sys.Date())), 'America/New_York') - 1L
# [1] "2018-01-12 23:59:59 EST"

关于r - Posixlt 和 Posixct 中的系统日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239834/

相关文章:

linux - bind() 选择零端口

r - 在 r 中应用函数太慢

r - 比较行以查看客户是否更换了产品

linux - Linux时间命令的结果

c - 使用 posix 而不是 fork/execv 运行 bash

python - 独立地执行 stdout 和 stderr,不增加抖动

r - data.table 后端的 dplyr 错误 [在 dplyr 0.4.3 或更早版本中]

r - R 中意外的应用函数行为

c++ - 计算线程内的时间

c++ - Linux:GetDateFormat() 和 GetTimeFormat() 是否存在 C++?