Suppose we have this input:
date <- c("2015-03-11", "2015-03-12") hour <- 2:3
then try one of them:
1) chron
library(chron) as.chron(date) + hour/24
giving:
[1] (03/11/15 02:00:00) (03/12/15 03:00:00)
2) POSIXct . In this case, only the R base is used, there are no packages:
as.POSIXct(date) + 3600 * hour
on my system:
[1] "2015-03-11 02:00:00 EDT" "2015-03-12 03:00:00 EDT"
If you want to get the result in the UTC time zone, use:
as.POSIXct(date, tz = "UTC") + 3600 * hour
3) lubridate
library(lubridate) ymd(date) + hours(hour)
giving:
[1] "2015-03-11 02:00:00 UTC" "2015-03-12 03:00:00 UTC"
If you want in the current time zone, then:
ymd(date, tz = "") + hours(hour)
Note that the chron solution provides a date / time class that does not use time zones, eliminating many of the problems that time zones can cause. POSIXct and lubridate solutions give the date / time in a specific time zone, as shown.
G. grothendieck
source share