Here, we will discuss dates and times in R with Sys.time(), Sys.Date(), strptime(), format(), as.Date(), and ISOdatetime() functions.

All the functions above are available in the "base" package, hence, no need for additional updates.

Summary of Functions for Dates and Times in R
Function Usage
Sys.time() Show the current date and time
Sys.Date() Show the current date
strptime() Convert Character to dates and times
format() Convert dates and times to Character
ISOdatetime() Convert to dates and times from Numeric
as.Date() Convert Character to the Date class

1 System Time in R

The function Sys.time() is used to tell the current date and time in R.

For example:

Sys.time()
[1] "2017-07-24 15:21:46 EDT"

As can be seen above, the results include, the year, month, day, hour, minute, second and time zone. It is of the "POSIXct" class which represents the (signed) number of seconds since the beginning of 1970 (in the UTC time zone) as a numeric vector.

1.1 How to Extract Components of Sys.time()

You can extract the various components of date and time using the unclass() function after converting to the "POSIXlt" class using as.POSIXlt(). The "POSIXlt" class is a named list of vectors representing the components of date and time.

This includes seconds 0-61 (including leap seconds), minutes 0-59, hour 0-23, month day 1-31, month 0-11, years since 1900, weekday 0-6 (starting Sunday = 0), year day 0-365, check if it is daylight savings, time zone, GMT offset in seconds.

timenow = Sys.time()
timenow = as.POSIXlt(timenow)
unclass(timenow)
$sec
[1] 46.86436

$min
[1] 21

$hour
[1] 15

$mday
[1] 24

$mon
[1] 6

$year
[1] 117

$wday
[1] 1

$yday
[1] 204

$isdst
[1] 1

$zone
[1] "EDT"

$gmtoff
[1] -14400

attr(,"tzone")
[1] ""    "EST" "EDT"
attr(,"balanced")
[1] TRUE

To extract the minutes of the hour, or days of the year and so on based on the component formats above, you can do the following:

datelist = unclass(timenow)
datelist$min
[1] 21
datelist$yday
[1] 204

1.2 System Date Only

For system date only, you can use:

Sys.Date()
[1] "2017-07-25"

As can be seen above, the results include, only the year, month, and day, and it is of the "Date" class which represents the (signed) number of days since the beginning of 1970 as a numeric vector where negative values represent earlier days compared to the referenced point.

1.3 Checking Code’s Run Time Using Sys.time()

You can check your code’s run time using the Sys.time() function. All you need to do is take the system time before running the code and after the code is finished running, and then take the difference.

For example, to check the run time for R to count from 1 to 1 million:

start_time = Sys.time()
i = 0
while(i<1000000){
  i=i+1
}
end_time = Sys.time()

run_time = end_time - start_time 
# Or
run_time = difftime(end_time, start_time)

run_time
Time difference of 0.02585602 secs

2 Conversion to and from Dates in R

Here we discuss how to convert Characters to Dates or from Dates to Characters.

First a table of format specification guides that will be applied in the examples below.

2.1 Conversion Format Symbols

Examples using "4/21/84 15:36:41" and the format symbols in the tables below.

date = "4/21/84 15:36:41"
date_form = strptime(date, "%m/%d/%y %H:%M:%S")
date_form
[1] "1984-04-21 15:36:41 EST"
format(date_form, "%Y")
[1] "1984"
format(date_form, "%B")
[1] "April"
Summary of Format Symbols for Dates and Times in R
Format Meaning Examples
%Y Year in 4 digits 1984
%y Year in 2 digits 84
%m Month in Numbers (1 or 2 digits) 04
%B Month in Letters in Full April
%b Month in Letters in Abbreviation Apr
%d Day in Numbers (1 or 2 digits) 21
%H Hours (24 hours, 1 or 2 digits) 15
%I Hours (12 hours, 1 or 2 digits) 03
%M Minutes (1 or 2 digits) 36
%S Seconds (1 or 2 digits) 41
%p AM/PM (Locale-specific) PM
Additional Format Symbols for Dates and Times in R
Format Meaning Examples
%e Day’s Number in the Month 21
%j Day’s Number in the Year (001 to 366) 112
%A Weekday in Letter in Full Saturday
%a Weekday in Letter in Abbreviation Sat
%u Weekday in Number (1-7, Monday is 1) 6
%w Weekday in Number (0-6, Sunday is 0) 6
%U Week’s Number (00-53, 01 = 1st Sunday) 16
%W Week’s Number (00-53, 01 = 1st Monday) 16
%c Date and Time (Locale-specific) Sat Apr 21 15:36:41 1984
%x Date (Locale-specific) 4/21/1984”
%D Date in "%m/%d/%y" Format 04/21/84
%F Date in "%Y-%m-%d" Format 1984-04-21
%v Date in "%d-%b-%Y" Format 21-Apr-1984
%X Time (Locale-specific) 3:36:41 PM
%R Time in "%H:%M" Format 15:36
%T Time in "%H:%M:%S" Format 15:36:41
%C Century in Number 19
%z UTC or GMT offset -0500 (EST offset vs UTC)
%t Add or Represent Tab

2.2 Converting Various Character Formats to Standard Dates and Times Using strptime()

You can convert dates and times of various Character formats to dates and times of the "POSIXlt" class using the strptime() function.

For example, using the format symbols in the tables above to represent the Character entry "Thu, 25 Jun 2009 02:36:38":

strptime("Thu, 25 Jun 2009 20:36:38",
         format = "%a, %d %b %Y %H:%M:%S")
[1] "2009-06-25 20:36:38 EDT"

You can further specify UTC (or GMT) offset with "%z", and the time zone with the "tz" argument. Time will be adjusted based on the offset and the difference between the specified or locale time zone and UTC.

In the examples below, we have an offset as "-0230", meaning the time zone is 2 hours and 30 minutes behind UTC (or GMT) time.

When the UTC time zone is specified, the 2 hours, 30 minutes delay is added back:

strptime("Thu, 25 Jun 2009 20:36:38 -0230",
         format = "%a, %d %b %Y %H:%M:%S %z", tz = "UTC")
[1] "2009-06-25 23:06:38 UTC"

When the CET time zone is specified, time will be added back based on the difference of 2 hours between UTC and CET (notice the date change):

strptime("Thu, 25 Jun 2009 20:36:38 -0230",
         format = "%a, %d %b %Y %H:%M:%S %z", tz = "CET")
[1] "2009-06-26 01:06:38"

For alternate format examples:

dates <- c("4/21/84", "08/15/00", "07/23/99")
times <- c("15:36:01", "04:35:22", "4:16:2")
dates_times <- paste(dates, times)
strptime(dates_times, "%m/%d/%y %H:%M:%S")
[1] "1984-04-21 15:36:01 EST" "2000-08-15 04:35:22 EDT"
[3] "1999-07-23 04:16:02 EDT"

Convert POSIXlt to POSIXct class:

date_POSIXlt = strptime(dates_times, "%m/%d/%y %H:%M:%S")
as.POSIXct(date_POSIXlt)
[1] "1984-04-21 15:36:01 EST" "2000-08-15 04:35:22 EDT"
[3] "1999-07-23 04:16:02 EDT"

Convert POSIXlt to Date class:

as.Date(date_POSIXlt)
[1] "1984-04-21" "2000-08-15" "1999-07-23"

2.3 Converting Standard Dates and Times to Various Character Formats Using format()

You can extract various dates and times Character formats from dates and times of the "POSIXlt", "POSIXct" and "Date" classes using the format() function.

See format symbols in the tables above.

For example:

date_time = strptime(paste("4/21/84", "15:36:41"),
                     "%m/%d/%y %H:%M:%S")
format(date_time, "%A, %D, %I %p")
[1] "Saturday, 04/21/84, 03 PM"

Conversion including POSIXct class to Character:

format(date_time, "%j : %H:%M")
[1] "112 : 15:36"
format(as.POSIXct(date_time), "%j : %H:%M")
[1] "112 : 15:36"

Conversion including Date class to Character:

format(date_time, "%Y - %B")
[1] "1984 - April"
format(as.Date(date_time), "%Y - %B")
[1] "1984 - April"

You can also add or change century of dates, for example, changing century to 2100s with "21%y":

format(date_time, "%m/%d/21%y")
[1] "04/21/2184"

2.4 Converting to Dates and Times from Numeric Using ISOdatetime()

You can convert numerical values to dates and times of the "POSIXct" class using the ISOdatetime() function (interchangeable with ISOdate()) which is of the form ISOdatetime(year, month, day, hour, min, sec, tz = "").

See format symbols in the tables above.

For example:

ISOdate(year = 2014, month = 11, day = 10,
        hour = 02, min = 06, sec = 22, tz = "EST")
[1] "2014-11-10 02:06:22 EST"
# Or
ISOdate(2014, 11, 10, 02, 06, 22, "EST")
[1] "2014-11-10 02:06:22 EST"

2.5 Converting to Dates Using as.Date()

You can convert various Character date formats to the Date class.

See format symbols in the tables above.

For example, with your date and format as Character strings:

as.Date("December 9, 2002", format="%B %d, %Y")
[1] "2002-12-09"
as.Date("03Jan14", format="%d%b%y")
[1] "2014-01-03"
as.Date("2009/7/2", format="%Y/%m/%d")
[1] "2009-07-02"

You can also take in the "POSIXct" class.

POSDate = ISOdate(2014, 11, 10, hour = 02,
                  min = 06, sec = 22, tz = "UTC")

as.Date(POSDate)
[1] "2014-11-10"
as.Date(POSDate, tz = "EST") # Notice the change in date due to time zone difference.
[1] "2014-11-09"

3 Operations on Dates and Times in R

You can perform arithmetic, relational and statistical operations on dates and times in R.

3.1 Arithmetic and Relational Operations

You can perform basic operations of + and -, provided the two objects are of the same class.

See format symbols in the tables above.

For example, checking time differences or for the more recent date:

a = as.Date("2012-07-23", format = "%Y-%m-%d")
b = as.Date("09/14/86", format = "%m/%d/%y")
a - b
Time difference of 9444 days
a < b
[1] FALSE
a = as.POSIXct("2019-08-01 12:31:08 EDT")
b = as.POSIXct("2018-03-21 22:37:23 EDT")
b - a
Time difference of -497.579 days
difftime(a, b, units = "hours") # takes ("secs", "mins", "hours", "days", "weeks")
Time difference of 11941.9 hours
a > b
[1] TRUE

Adding days to a Date class object:

a = as.Date("2012-07-23", format = "%Y-%m-%d")
a + 5
[1] "2012-07-28"

Removing seconds from a POSIXct or POSIXlt object:

a = as.POSIXct("2019-08-01 12:31:08 EDT")
a - 30
[1] "2019-08-01 12:30:38 EDT"

3.2 Statistical Operations

You can also perform statistical operations such as min, max, mean, median, range etc., on dates and times in R.

a = as.POSIXct("2019-08-01 12:31:08 EDT")
b = as.POSIXct("2018-03-21 22:37:23 EDT")
c = as.POSIXct("2020-06-04 09:36:44 EDT")
min(c(a, b, c))
[1] "2018-03-21 22:37:23 EDT"
max(c(a, b, c))
[1] "2020-06-04 09:36:44 EDT"
mean(c(a, b, c))
[1] "2019-05-30 06:55:05 EDT"
median(c(a, b, c))
[1] "2019-08-01 12:31:08 EDT"
range(c(a, b, c))
[1] "2018-03-21 22:37:23 EDT" "2020-06-04 09:36:44 EDT"

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes