如何从POSIXlt时间添加/减少时间,同时将其类保留在R中? [英] How to add/subtract time from a POSIXlt time while keeping its class in R?

查看:246
本文介绍了如何从POSIXlt时间添加/减少时间,同时将其类保留在R中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在操纵一些 POSIXlt DateTime对象。例如,我想添加一个小时:

I am manipulating some POSIXlt DateTime objects. For example I would like to add an hour:

my.lt = as.POSIXlt("2010-01-09 22:00:00")
new.lt = my.lt + 3600
new.lt
# [1] "2010-01-09 23:00:00 EST"
class(new.lt)
# [1] "POSIXct" "POSIXt" 

我想要的是 new.lt 成为一个 POSIXlt 对象。我知道我可以使用 as.POSIXlt 将其转换回 POSIXlt ,但是是否有更优雅有效的方式要实现这个?

The thing is I want new.lt to be a POSIXlt object. I know I could use as.POSIXlt to convert it back to POSIXlt, but is there a more elegant and efficient way to achieve this?

推荐答案

简答:否

POSIXct POSIXlt 对象是两种特定类型的更一般的 POSIXt 类(不是严格的面向对象的继承意义,而是在面向对象的实现方面)。代码之间可以自由切换。当您添加到 POSIXlt 对象时,实际使用的函数是 +。POSIXt ,不是专门为 POSIXlt 。在这个函数内,参数被转换成一个 POSIXct ,然后处理(添加到)。

POSIXct and POSIXlt objects are two specific types of the more general POSIXt class (not in a strictly object oriented inheritance sense, but in a quasi-object oriented implementation sense). Code freely switches between these. When you add to a POSIXlt object, the actual function used is +.POSIXt, not one specifically for POSIXlt. Inside this function, the argument is converted into a POSIXct and then dealt with (added to).

此外, POSIXct 是从特定日期和时间开始的秒数。 POSIXlt 是日期部分的列表(秒,分,小时,月,月,年,星期几,日,DST信息),所以添加到直接没有任何意义。将它转换成几秒钟( POSIXct ),并添加到这一点是有道理的。

Additionally, POSIXct is the number of seconds from a specific date and time. POSIXlt is a list of date parts (seconds, minutes, hours, day of month, month, year, day of week, day of year, DST info) so adding to that directly doesn't make any sense. Converting it to a number of seconds (POSIXct) and adding to that does make sense.

这篇关于如何从POSIXlt时间添加/减少时间,同时将其类保留在R中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆