如何计算R中两个日期之间的天数

问题描述:

我正在尝试减去R中的两个日期。这是通过structure命令的两个日期:

I'm trying to subtract two dates in R. These are the two dates via the structure command:

str(standard_data_4testing$start_datetime)
 POSIXct[1:489124], format: "2016-02-01 00:38:49" "2016-02-01 07:48:53" "2016-02-01 08:32:08" "2016-02-01 11:21:13" ...

str(standard_data_4testing$original_installdate)
 Date[1:489124], format: "2015-10-15" "2015-10-15" "2015-10-15" "2016-01-29" "2016-01-29" "2016-01-29" ...

我在R中都是使用 as.Date 函数创建的,但 start_datetime 具有日期和时间,而 original_installdate 仅在原始数据中具有日期,如上所示。

I created both with as.Date functions in R but start_datetime has date and time and original_installdate only has date in the original data as reflected above.

是否可以减去它们?

我尝试使用以下语句减去:

I tried to subtract using this statement:

standard_data_4testing$start_datetime - standard_data_4testing$original_installdate

但我收到此错误:


警告消息:-

Warning message: Incompatible methods ("-.POSIXt", "-.Date") for "-"


$的方法( -.POSIXt,-。Date)不兼容b $ b

打印出一些数据后:

after it prints out some data:


[6049] 2016-02-01 09:48:44 UTC 2016-02-01 07:24:08 UTC 2016-02-01
09:02:33 UTC 2016-02-01 09:14:29 UTC [6053] 2016- 02-01 10:49:46
UTC 2016-02-01 19:07:52 UTC 2016-02-01 02:39:04 UTC 2016-02-01
03:59:29 UTC [6057] 2016-02-01 07:13:05 UTC 2016-02-01 07:58:50
UTC不适用

[6049] "2016-02-01 09:48:44 UTC" "2016-02-01 07:24:08 UTC" "2016-02-01 09:02:33 UTC" "2016-02-01 09:14:29 UTC" [6053] "2016-02-01 10:49:46 UTC" "2016-02-01 19:07:52 UTC" "2016-02-01 02:39:04 UTC" "2016-02-01 03:59:29 UTC" [6057] "2016-02-01 07:13:05 UTC" "2016-02-01 07:58:50 UTC" NA

我也尝试过使用POSIXct,但收到类似的错误。

I've also tried using POSIXct but received a similar error.

有什么方法可以减去两个日期,尽管它们的成分有所不同?

Is there any way I can subtract the two dates, despite the differences in their components?

感谢您的帮助

首先将两个日期都转换为 POSIXct 类。确保在同一时区进行计算,POSIXt类默认为您的语言环境时区, as.Date 默认为UTC。

Convert both dates to the POSIXct class first. Be sure to do the calculations in the same timezone, the POSIXt classes default to your locale timezone, as.Date defaults to UTC.

test1 <- as.Date("2016-01-01", tz="UTC")
test2 <- strptime("2016-01-02", format="%Y-%m-%d", tz="UTC")
difftime(as.POSIXct(test2), as.POSIXct(test1, tz="UTC"), units="days")
# Time difference of 1 days