R Posixlt和Posixct中的系统日期

R Posixlt和Posixct中的系统日期,r,time,posix,lubridate,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.

我试图在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.Posixct
as.Posixlt
使用
Sys.Date()
返回两个不同的值,为什么即使在
lubridate
中应用
force_tz
8小时后仍然存在差异

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


这可以归结为一些微妙的事情发生了;从
?as.POSIXlt.Date

没有时间的日期被视为UTC午夜

因此

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

奇怪的是这不能被重写--
as.POSIXlt.Date
不接受
tz
参数:

formals(as.POSIXlt.Date)
# $x
# $...

如果您想使用POSIXct
POSIXct
,那么以下内容如何

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

@在黑暗中,我终于满足于我的回答,因为它涵盖了你的问题;如果我遗漏了什么,请跟进
force_tz(as.POSIXct(sprintf('%s 00:00:00', Sys.Date())), 'America/New_York') - 1L
# [1] "2018-01-12 23:59:59 EST"