Built with Tutify.io

    AIStudyLabs

    Dates and Times in R with Examples

    Dates and Times in R with Examples

    Times in R are represented by the POSIXct or POSIXlt class and Dates are represented by the Date class. The as.Date() function handles dates in R without time. This function takes the date as a String in the format YYYY-MM-DD or YYY/MM/DD and internally represents it as the number of days since 1970-01-01. And, Times are stored internally as the number of seconds since 1970-01-01.

    In this article, I will explain how to work with Dates and Times in R Programming Language by creating Dates and Times, manipulating, formatting, date and time operations e.t.c.

    Facts of Dates and Times in R

    Following are the Date formats that are used to specify the date, I will use these in the examples below.

    | Code | Meaning | Code | Meaning | | --- | --- | --- | --- | | %a | Abbreviated weekday | %A | Full weekday | | %b | Abbreviated month | %B | Full month | | %c | Locale-specific date and time | %d | Decimal date | | %H | Decimal hours (24 hour) | %I | Decimal hours (12 hour) | | %j | Decimal day of the year | %m | Decimal month | | %M | Decimal minute | %p | Locale-specific AM/PM | | %S | Decimal second | %U | Decimal week of the year (starting on Sunday) | | %w | Decimal Weekday (0=Sunday) | %W | Decimal week of the year (starting on Monday) | | %x | Locale-specific Date | %X | Locale-specific Time | | %y | 2-digit year | %Y | 4-digit year | | %z | Offset from GMT | %Z | Time zone (character) |

    1. Dates in R

    The as.Date() function handles dates in R without time. This function takes the date as a String in the format YYYY-MM-DD or YYY/MM/DD and internally represents it as the number of days since 1970-01-01.

    So Date 1970-01-01 stores as 0, 1970-01-02 stores as 1. Let's check this with an example.

    The default input format for Date consists of the year, followed by the month and day, separated by slashes or dashes.

    
    # Date examples
    x <- as.Date("1970-01-01")
    y <- as.Date("1970-01-02")
    print(x)
    print(y)
    

    Yields below output. Note that typeof(x) returns a double value. And, class(x) returns Date.

    To check the internal value of these dates, use the unclass() function.

    
    # Check internal value of date
    unclass(x)
    unclass(y)
    

    Yields below output.

    1.1 Dates not in Standard Format

    If your input dates are not in the standard format, you have the specify the format as shown below.

    
    z <- as.Date("01/01/1970",format='%m/%d/%Y')
    print(z)
    

    2. Times in R

    Times are stored internally as the number of seconds since 1970-01-01. Times in R are represented either by the POSIXct or the POSIXlt class. Let's see with examples what each time class brings to us.

    POSIXct stores the time as a large integer value whereas POSIXlt stores the time as a list of values with information like day, month, week, year e.t.c. If you wanted to get a specific value of time this comes in handy.

    The default input format for POSIX dates consists of the year, followed by the month and day, separated by slashes or dashes; for time values, the date may be followed by white space and a time in the form hour:minutes:seconds or hour:minutes followed by timezone.

    2.1 POSIXct Time Class

    The as.POSIXct() function takes date and time as input and returns the time of the type class POSIXct, it internally represents the time as a large integer value. Use the unclass() to check the integer value.

    
    # Using POSIXct
    timect <- as.POSIXct("2022-11-08 22:14:35 PST")
    print(timect)
    class(timect)
    unclass(timect)
    

    Yields below output.

    2.2 POSIXlt Time Class

    The as.POSIXlt() function also takes the date and time as string format and returns a value of type class POSIXlt, it internally stores the values of data and time parts as a list which ideally contains day, week, month, year, hour, minute, and the second e.t.c. You can check these values by calling unclass().

    
    # Using as.POSIXlt
    timelt <- as.POSIXlt("2022-11-08 22:14:35 PST")
    print(timelt)
    class(timelt)
    unclass(timelt)
    

    Yields below output.

    3. Operations on Dates & Times in R

    You can perform several mathematic operations like + and - on Dates & Times and you can do comparisons too like ==, >, < e.t.c. Following are some examples.

    3.1 Subtract Dates in R

    In the below example, I am subtracting the date from another date which results in differences in the number of days.

    
    # Date Diff
    dateDiff <- as.Date("2021-01-01") - as.Date("2020-01-01")
    print(dateDiff)
    
    # Output
    # Time difference of 366 days
    

    3.2 Subtract Times in R

    Now let's use subtract time from another time, the result would be in decimal value.

    
    #Time Diff
    x <- as.POSIXlt("2022-11-08 03:14:35 PST") 
    y <- as.POSIXlt("2022-11-09 26:14:35 PST") 
    timeDiff <- y - x
    print(timeDiff)
    
    # Output
    # Time difference of 20.75694 hours
    

    3.3 Extract Parts of Data & Time

    Since POSIXlt stores the time as an array by representing all date fields, you can use $ operator on the object to get the values. The fields you can use are "sec", "min", "hour", "mday", "mon", "year", "wday", "day", "isdst", "zone", "gmtoff".

    
    # Date & Time Values
    timelt$sec
    timelt$wday
    
    # Output
    #[1] 35
    #[1] 2
    

    3.4 Add Days to Dates

    By using the + operator let's add some days to the Date.

    
    # Add days to date
    newDate <- as.Date("2021-01-01") + 3
    print(newDate)
    
    # Output
    #[1] "2021-01-04"
    

    4. Dates & Times Functions in R

    Following are some of the Dates and Times functions in R.

    4.1 Sys.time()

    Sys.time() returns the current system date and time in the format "2022-11-09 20:05:17 PST" which is of type class "POSIXct" or "POSIXt"

    
    x <- Sys.time()
    print(x)
    class(x)
    

    4.2 Find Internal Between Dates

    If you have a vector of dates or times, you can use the diff() function to get the difference between dates. The result of the below example would be different between the first and second dates and the different between the second and third dates.

    
    # Differences
    datesVec <- as.Date(c("2020-04-21", "2021-06-30", "2021-11-04"))
    diff(datesVec)
    
    # Output
    #Time differences in days
    #[1] 435 127
    

    4.3 Generate Sequence of Dates

    By using seq() function you can generate the sequence of dates with the specified length. The below example generates 5 dates by month difference.

    
    dateMonth <- seq(as.Date("2020-04-21"), length = 5, by = "month")
    dateMonth
    
    # Output
    #[1] "2020-04-21" "2020-05-21" "2020-06-21" "2020-07-21" "2020-08-21"
    

    4.4 Truncate Date & Time

    The trunc() function is used to truncate the date and time values. The below examples demonstrate the truncation of days, months, and years.

    
    #truncate
    x <- as.POSIXlt("2022-11-08 03:14:35 PST") 
    trunc(x, "mins")
    trunc(x, "days")
    trunc(x, "year")
    
    # Output
    [1] "2022-11-08 03:14:00 PST"
    [1] "2022-11-08 PST"
    [1] "2022-01-01 PST"
    

    4.5 strptime()

    If you have dates and times in R with a different than standard format use strptime() to convert it to POSIXlt class. This function takes a character vector that has dates and times and converts into to a POSIXlt object.

    
    #strptime() function example
    strDate <- c("11 April, 2022 09:30", "20 November, 2022 10:05")
    x <- strptime(strDate, "%d %B, %Y %H:%M")
    print(x)
    class(x)
    

    Yields below output.

    5. Conclusion

    In this article you have learned different ways to represent date and times in R. Dates are represented by the Date class and Times are represented by the POSIXct or the POSIXlt class. Dates are stored internally as an integer representing number of days since 1970-01-01 and Times are stored internally as an integer representing number of seconds since 1970-01-01.

    You can find the complete example explained in this article at R GitHub Examples Project.

    Related Articles

    <a id="h-references"></a>

    References