将两个date_times的中点四舍五入到最接近的小时并保留hms

时间:2018-12-02 19:45:10

标签: r datetime lubridate posixct

我正在尝试将两个date_time的中点四舍五入到最接近的小时,并在输出中保留hms。

例如,在这里我希望中点为2016-01-15 00:00:00

library(lubridate)
Sys.setenv(TZ="Europe/London") #needing to establish TZ/use other TZs later on

start_datetime <- as.POSIXct("2016-01-13 08:00:00", tz = "Europe/London")
end_datetime   <- as.POSIXct("2016-01-16 15:00:00", tz = "Europe/London")

# using R's internal setting of 1970-01-01, gets 2016-01-14 23:30:00, 
# which seems right
midpoint <- as.POSIXct((as.numeric(end_datetime) + 
                      as.numeric(start_datetime)) / 2, origin = '1970-01-01') 

#gets 2016-01-15 only (no hms):
midpoint_nearesthour_fail1 <- round_date(midpoint, "hours") #lubridate function

#gets 2016-01-15 only (no hms):
midpoint_nearesthour_fail2 <- round(midpoint, "hours")  #base R function

#gets 2016-01-14 23:30:00 as above (as expected, with no rounding)
#but interestingly, if all three "Europe/London" replaced with "America/Los_Angeles",:
#gets: 2016-01-15 07:30:00
midpoint_nearesthour_fail3 <- as_datetime(midpoint) 

0 个答案:

没有答案