22  Dates and Times

Here, we will focus on how to handle dates and times using the Base R functions.

22.1 Classes for Dates and Times

R has a variety of classes for working with dates and times, which is nice if you prefer having a choice but annoying if you prefer living simply. There is a critical distinction among the classes: some are date-only classes, some are datetime classes. All classes can handle calendar dates (e.g., March 15, 2019), but not all can represent a datetime (e.g., 11:45 AM on March 1, 2019).

The following classes are included in the base distribution of R:

  • Date

    The Date class can represent a calendar date but not a clock time. It is a solid, general-purpose class for working with dates, including conversions, formatting, basic date arithmetic, and time-zone handling.

  • POSIXct

    This is a datetime class, and it can represent a moment in time with an accuracy of one second. Internally, the datetime is stored as the number of seconds since January 1, 1970, and so it’s a very compact representation. This class is recommended for storing datetime information (e.g., in data frames).

  • POSIXlt

    This is also a datetime class, but the representation is stored in a nine-element list that includes the year, month, day, hour, minute, and second. This representation makes it easy to extract date parts, such as the month or hour. Obviously, this is much less compact than the POSIXct class; hence, it is normally used for intermediate processing and not for storing data.

The base distribution also provides functions for easily converting between representations: as.Date(), as.POSIXct(), and as.POSIXlt().

If you prefer more advanced tools to handle dates and times, refer to the following helpful packages that are available for downloading from CRAN:

  • chron

    The chron package can represent both dates and times but without the added complexities of handling time zones and Daylight Saving Time. It’s therefore easier to use than Date but less powerful than POSIXct and POSIXlt. It would be useful for work in econometrics or time series analysis.

  • lubridate

    This is a tidyverse package designed to make working with dates and times easier while keeping the important bells and whistles such as time zones. It’s especially clever regarding datetime arithmetic. This package introduces some helpful constructs like duration, periods, and intervals. lubridate is part of the tidyverse, so it is installed when you install.packages('tidyverse') but it is not part of “core tidyverse”, so it does not get loaded when you run library(tidyverse). This means you must explicitly load it by running library(lubridate).

  • mondate

    This is a specialized package for handling dates in units of months in addition to days and years. It can be helpful in accounting and actuarial work, for example, where month-by-month calculations are needed.

  • timeDate

    This is a high-powered package with well-thought-out facilities for handling dates and times, including date arithmetic, business days, holidays, conversions, and generalized handling of time zones. It was originally part of the Rmetrics software for financial modeling, where precision in dates and times is critical. If you have a demanding need for date facilities, consider this package.

Which class should you select? The article “Date and Time Classes in R” by Gabor Grothendieck and Thomas Petzoldt offers this general advice:

When considering which class to use, always choose the least complex class that will support the application. That is, use Date if possible, otherwise use chron and otherwise use the POSIX classes. Such a strategy will greatly reduce the potential for error and increase the reliability of your application.

Exercise G

Q1
  1. Utilize the Sys.Date() function to retrieve the current date and the Sys.time() function to capture the current time.
  2. Examine the classes of the values returned by these functions.
Note

You may encounter the term “POSIXt” in the output. In the R programming environment, “POSIXt” is a virtual class from which the “POSIXct” and “POSIXlt” classes inherit. This structure facilitates operations, such as subtraction, that require the interaction of the two derived classes.

22.2 Converting a string into a date

You can use the as.Date() function to convert a string, such as “2021-01-01”, to a Date object. However, you must know the format of the string. By default, as.Date() assumes the string looks like yyyy-mm-dd. To handle other formats, you must specify the format parameter of as.Date(). Use format = "%m/%d/%Y" if the date is in American style, for instance.

The following example shows the default format assumed by as.Date(), which is the ISO 8601 standard format of yyyy-mm-dd.

as.Date("2021-01-01")
[1] "2021-01-01"

The as.Date() function returns a Date object that is being converted here back to a string for printing; this explains the double quotes around the output.

The string can be in other formats, but you must provide a format argument so that as.Date() can interpret your string. Americans often mistakenly try to convert the usual American date format (mm/dd/yyyy) into a Date object, with these unhappy results:

as.Date("01/01/2021")
[1] "1-01-20"

Here is the correct way to convert an American-style date:

as.Date("01/01/2021", format = "%m/%d/%Y")
[1] "2021-01-01"

Observe that the Y in the format string is capitalized to indicate a four-digit year. If you’re using two-digit years, specify a lowercase y.

Exercise H

Q1

Convert each element in the following vector to Date object:

["2024.10.1", "2024.10.2", "2024.10.3", "2024.10.4", "2024.10.5"].

Each string represents a date and should be appropriately transformed into an object of the Date class.

22.3 Converting Year, Month and Day into a Date

It is common for the input data to contain dates encoded as three numbers: year, month, and day. The ISOdate() function can combine them into a POSIXct object:

ISOdate(2020, 2, 29)
[1] "2020-02-29 12:00:00 GMT"

You can keep your date in the POSIXct format. However, when working with pure dates (not dates and times), we often convert to a Date object and truncate the unused time information:

as.Date(ISOdate(2020, 2, 29))
[1] "2020-02-29"

Trying to convert an invalid date results in NA:

ISOdate(2023, 2, 29) # 2023 is not a leap year
[1] NA

When we have a date represented by its year, month, and day in different variables and would like to merge these elements into a single Date object representation, we should think of the ISOdate() function. Its output is a POSIXct object that you can convert into a Date object:

year <- 2024
month <- 12
day <- 31

# the output of ISOdate is POSIXct
class(ISOdate(year, month, day))
[1] "POSIXct" "POSIXt" 
# we can further convert it to Date
as.Date(ISOdate(year, month, day))
[1] "2024-12-31"

ISOdate() can process entire vectors of years, months, and days, which is quite handy for mass conversion of input data. The following example starts with the year/month/day numbers and then combines them all into Date objects.

years <- rep(2024, 5)
months <- 1:5
days <- c(15, 21, 20, 18, 17)
ISOdate(years, months, days)
[1] "2024-01-15 12:00:00 GMT" "2024-02-21 12:00:00 GMT"
[3] "2024-03-20 12:00:00 GMT" "2024-04-18 12:00:00 GMT"
[5] "2024-05-17 12:00:00 GMT"
# convert to Date
as.Date(ISOdate(years, months, days))
[1] "2024-01-15" "2024-02-21" "2024-03-20" "2024-04-18" "2024-05-17"

Purists will note that the vector of years is redundant and that the last expression can therefore be further simplified by invoking the Recycling Rule:

as.Date(ISOdate(2024, months, days))
[1] "2024-01-15" "2024-02-21" "2024-03-20" "2024-04-18" "2024-05-17"

You can also extend this recipe to handle year, month, day, hour, minute, and second data by using the ISOdatetime() function (see the help page for details).

ISOdatetime(2024, 10, 01, 21, 30, 59)
[1] "2024-10-01 21:30:59 UTC"

Exercise I

Q1

We have defined the following variables:

Year <- 2024
Day <- 1:10
Month <- rep(1:12, each = length(Day))

Using these elements, your task is to generate a vector comprising Date objects. Ensure that you properly combine the Year, Month, and Day variables to construct valid date representations.

Q2

Begin by copying the following code into your R session:

logtime <- data.frame(Year = 2024,
                      Month = rep(1:12, each = 5),
                      Day = 15,
                      Hour = seq(10, 18, by = 2),
                      Min = 30,
                      Sec = 45)

Your next task is to merge all the existing columns into a new column in this dataframe. The new column should represent the datetime information from all the columns in POSIXct format. You can name this new column DTinfo.

22.4 Converting a date into a string

Sometimes we also want to convert a Date object into a character string, usually because we want to print the date. Either the function format() or as.character() would help us with this.

format(Sys.Date())
[1] "2024-12-02"
as.character(Sys.Date())
[1] "2024-12-02"

Both functions allow a format argument that controls the formatting. We can use format = "%m/%d/%Y" to get American-style dates, for example:

format(Sys.Date(), format = "%m/%d/%Y")
[1] "12/02/2024"

The format argument defines the appearance of the resulting string. Normal characters, such as slash (/) or hyphen (-) are simply copied to the output string. Each two-letter combination of a percent sign (%) followed by another character has special meaning. Some common ones are:

  • %b: Abbreviated month name (“Jan”)
  • %B: Full month name (“January”)
  • %d: Day as a two-digit number
  • %m: Month as a two-digit number
  • %y: Year without century (00–99)
  • %Y: Year with century

See the help page for the strftime() function for a complete list of formatting codes.

Exercise J

Q1

Extract the first column from the ggplot2::economics data frame and convert it into a character type, formatting the dates to resemble “Jul 01, 1967”. Ensure that each date entry is transformed into this specific string format.

22.5 Getting the Julian date

Given a Date object, we can extract the Julian date - which is, in R, the number of days since January 1, 1970, using either the as.integer() or the julian() function:

as.integer(as.Date("2024-01-01"))
[1] 19723
julian(as.Date("2024-01-01"))
[1] 19723
attr(,"origin")
[1] "1970-01-01"

Exercise K

Q1

Find the Julian date of Jan 1, 1970.

22.6 Extracting parts of a date

Given a Date object, you can extract a date part such as the day of the week, the day of the year, the calendar day, the calendar month, or the calendar year.

To do this, conversion to a POSIXlt object would be helpful. Recall that POSIXlt stores date elements in a list. Extracting the desired part in a date is just like extracting it from the list:

dt <- as.Date("2023-12-31")
plt <- as.POSIXlt(dt)
# Day of the month
plt$mday
[1] 31
# Month (0 = January)
plt$mon
[1] 11
# Year
plt$year + 1900
[1] 2023

The POSIXlt object represents a date as a list of date parts. Convert your Date object to POSIXlt by using the as.POSIXlt() function, which will give you a list with these members:

  • sec: Seconds (0-61)
  • min: Minutes (0-59)
  • hour: Hours (0-23)
  • mday: Day of the month (1-31)
  • mon: Month (0-11)
  • year: Years since 1900
  • wday: Day of the week (0-6, 0 = Sunday)
  • yday: Day of the year (0-365)
  • isdst: Daylight Saving Time flag

Exercise L

Q1

Determine the day of the week for December 31, 2024, and identify its numerical position within that year (i.e., ascertain which day of the year it is).

22.7 Creating a sequence of dates

Sometimes we need to create a sequence of dates, such as a sequence of daily, monthly, or annual dates. The seq() function is a generic function that has a version for Date objects. It can create a Date sequence similarly to the way it creates a sequence of numbers.

A typical use of seq() specifies a starting date (from), ending date (to), and increment (by). An increment of 1 indicates daily dates:

fromdt <- as.Date("2020-02-01")
todt <- as.Date("2020-03-01")
seq(from = fromdt, to = todt, by = 1)
 [1] "2020-02-01" "2020-02-02" "2020-02-03" "2020-02-04" "2020-02-05"
 [6] "2020-02-06" "2020-02-07" "2020-02-08" "2020-02-09" "2020-02-10"
[11] "2020-02-11" "2020-02-12" "2020-02-13" "2020-02-14" "2020-02-15"
[16] "2020-02-16" "2020-02-17" "2020-02-18" "2020-02-19" "2020-02-20"
[21] "2020-02-21" "2020-02-22" "2020-02-23" "2020-02-24" "2020-02-25"
[26] "2020-02-26" "2020-02-27" "2020-02-28" "2020-02-29" "2020-03-01"

Another typical use specifies a starting date (from), increment (by), and number of dates (length.out):

seq(from = fromdt, by = 1, length.out = 7)
[1] "2020-02-01" "2020-02-02" "2020-02-03" "2020-02-04" "2020-02-05"
[6] "2020-02-06" "2020-02-07"

The increment (by) is flexible and can be specified in days, weeks, months, or years:

fromdt <- as.Date("2024-01-01")
# First day of each month in one year
seq(from = fromdt, by = "month", length.out = 12)
 [1] "2024-01-01" "2024-02-01" "2024-03-01" "2024-04-01" "2024-05-01"
 [6] "2024-06-01" "2024-07-01" "2024-08-01" "2024-09-01" "2024-10-01"
[11] "2024-11-01" "2024-12-01"
# Quarterly dates for one year
seq(from = fromdt, by = "3 months", length.out = 4)
[1] "2024-01-01" "2024-04-01" "2024-07-01" "2024-10-01"
# Year-start dates for one decade
seq(from = fromdt, by = "year", length.out = 10)
 [1] "2024-01-01" "2025-01-01" "2026-01-01" "2027-01-01" "2028-01-01"
 [6] "2029-01-01" "2030-01-01" "2031-01-01" "2032-01-01" "2033-01-01"

Be careful with by = "month" near month-end. In the following example, the end of February overflows into March, which is probably not what you wanted:

seq(as.Date("2023-01-29"), by = "month", length.out = 3)
[1] "2023-01-29" "2023-03-01" "2023-03-29"

Exercise M

Q1

Create a sequence of quarterly dates spanning three years, starting from January 1, 2000.