从 POSIXlt 对象减去时间

Drops time when subtracting from POSIXlt object

我正在尝试从这个定义为 01:00 的时间对象中减去一个小时(3600 秒)。当我这样做时,时间部分消失了,只剩下日期了。我需要保留时间部分——我该怎么做?只有当我的减法结果是 00-00 时才会发生这种情况。

test <- strptime("2016-09-02_01-00", format =  "%Y-%m-%d_%H-%M", tz = "UTC")
test
[1] "2016-09-02 01:00:00 UTC"
test-3600
[1] "2016-09-02 UTC"

这是内容和表示之间的区别。

fmt <- "%Y-%m-%d_%H-%M"
test <- strptime("2016-09-02_01-00", 
     format = fmt, tz = "UTC")
str(test)
## POSIXlt[1:1], format: "2016-09-02 01:00:00"

减去 3600 会改变结构(从 POSIXltPOSIXct)...

str(test-3600)
## POSIXct[1:1], format: "2016-09-02"

...但格式的变化只是由于 R 试图提供帮助并打印最简单的可用表示形式。时间信息实际上并没有消失。来自 ?strptime(感谢@DavidArenburg):

The default for the format methods is "%Y-%m-%d %H:%M:%S" if any element has a time component which is not midnight, and "%Y-%m-%d" otherwise

正如@MrFlick 在评论中所述,您可以通过指定格式字符串来覆盖它...

fmt2 <- "%Y-%m-%d %H:%M:%S"
format(test-3600,fmt2)
## [1] "2016-09-02 00:00:00"