Search code examples
rdatetimeposixctdate-conversion

R package constructing time objects from date and hour(integer)


I have data provided in the form of a date telling the day (format "YYYY-MM-DD", e.g. "2015-03-11" and the hours of the day numbered (0-23).

What is the most convenient way to produce time objects of the form

"2015-03-11" and hour = 0 ->  "2015-03-11 00:00"
"2015-03-11" and hour = 1 ->  "2015-03-11 01:00"
"2015-03-11" and hour = 2 ->  "2015-03-11 02:00"

I could use the Date function from Base or something from xts or timeDate. Should be easy but I am sure someone out there knows it quickly.

EDIT: the data is provided in 2 columns, one for the date and one numerical.


Solution

  • Suppose we have this input:

    date <- c("2015-03-11", "2015-03-12")
    hour <- 2:3
    

    then try one of these:

    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. This one only uses the base of R, no packages:

    as.POSIXct(date) + 3600 * hour    
    

    giving, on my system:

    [1] "2015-03-11 02:00:00 EDT" "2015-03-12 03:00:00 EDT"
    

    If you wanted 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 it in the current time zone then:

    ymd(date, tz = "") + hours(hour)
    

    Note that the chron solution gives a date/time class that does not use time zones eliminating the many problems that time zones can cause. The POSIXct and lubridate solutions give the date/time in a specific time zone as shown.