[1] "2021-01-01"
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:
DateThe
Dateclass 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.POSIXctThis is a
datetimeclass, 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).POSIXltThis is also a
datetimeclass, 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 thePOSIXctclass; 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:
chronThe
chronpackage 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 thanDatebut less powerful thanPOSIXctandPOSIXlt. It would be useful for work in econometrics or time series analysis.lubridateThis is a
tidyversepackage 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.lubridateis part of thetidyverse, so it is installed when youinstall.packages('tidyverse')but it is not part of “coretidyverse”, so it does not get loaded when you runlibrary(tidyverse). This means you must explicitly load it by runninglibrary(lubridate).mondateThis 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.
timeDateThis 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
Rmetricssoftware 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
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.
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:
Here is the correct way to convert an American-style date:
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
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:
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:
Trying to convert an invalid date results in 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"
[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.
[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"
[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:
[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).
Exercise I
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.
Both functions allow a format argument that controls the formatting. We can use format = "%m/%d/%Y" to get American-style dates, for example:
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
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:
[1] 19723
[1] 19723
attr(,"origin")
[1] "1970-01-01"
Exercise K
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:
[1] 31
[1] 11
[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 1900wday: Day of the week (0-6, 0 = Sunday)yday: Day of the year (0-365)isdst: Daylight Saving Time flag
Exercise L
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:
[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):
[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"
[1] "2024-01-01" "2024-04-01" "2024-07-01" "2024-10-01"
[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: