Chapter 15 Dates and Times in R

15.1 What makes dates and times special

Dates and times can be a headache to work with. They may look just like numbers, but they don’t follow regular number rules. Here’s just a handful of things that make dates and times different:

  • There’s no 61 after 60 when working with seconds and minutes;
  • There’s no 25 after 24 when working with hours;
  • There’s no 13 after 12 when working with months;
  • Most years are 365-days long, but some are 366-days long;
  • The same time means something different depending on the time zone;
  • The same time means something different between standard and daylight savings time. And daylight savings time starts on a different day each year.

Keeping track of these rules manually would be a nightmare, especially when working with large datasets. In this Chapter we’re going to learn how to reproducibly deal with dates and times in R by treating these data types as the special kind that they are.

15.2 Definitions

Let’s start with some definitions that I’ll use throughout this Chapter:

  • Date: this type of data contains information on day, month, and year;
  • Time: this type of data contains information on hour, minute, and second;
  • Timestamp: this type of data contains information on both date and time (day, month, year, hour, minute, second);
  • Date-time: a generic term I use to refer to anything that is either a date, a time, or a timestamp.

15.3 Under the hood

As you may remember from Chapter 4, Excel stores dates and times in a spreadsheet as numbers. While what you see may be something of the format “2021-04-15”, the actual data stored under the hood is a number: specifically, the number of days between a reference date (which is 12/31/1899 on Windows and 12/31/1903 on Mac) and the date in the spreadsheet. In R, something similar happens. Base R has two basic classes for date/times, called POSIXct and POSIXlt. POSIXct is the number of seconds since 1/1/1970 00:00:00 (this can be negative for dates before that day, so any dates are supported). POSIXlt is a named list of vectors representing second, minute, hour, day of the month, months since January, years since 1900, day of the week, day of the year, and a flag defining whether it’s daylight savings time or not. For instance:

d <- "2021-04-15"

class(d)
## [1] "character"

If I just write out a date in quotes, this is still just a character string.

d <- as.POSIXct(d)

class(d)
## [1] "POSIXct" "POSIXt"
d
## [1] "2021-04-15 MDT"

But if I convert that character string into POSIXct, now R understands it is a date. What is displayed is the date in my current time zone (which R knows):

Sys.timezone()
## [1] "America/Denver"

But what’s actually hiding under that date is the number of seconds from 1/1/1970. Let’s see what happens if I convert my date to POSIXlt instead:

d <- as.POSIXlt(d)

class(d)
## [1] "POSIXlt" "POSIXt"
d
## [1] "2021-04-15 MDT"

What’s displayed doesn’t change, but the way R is storing the information under the hood is different.

You may have noticed that each time I converted to POSIXct or POSIXlt R also added the class POSIXt to the object. POSIXt is a class that inherits some properties from both POSIXct and POSIXlt, and it makes operations between the two possible.

Here is how to do the same thing with a date-time string:

dt <- "2021-04-15 13:20:00"

as.POSIXct(dt)
## [1] "2021-04-15 13:20:00 MDT"
as.POSIXlt(dt)
## [1] "2021-04-15 13:20:00 MDT"

Besides POSIXct and POSIXlt, R also support a data type called Date. This is equivalent to Excel’s handling of dates, i.e., the number of days since 1/1/1970:

d <- "2021-04-15"

as.Date(d)
## [1] "2021-04-15"

This data type makes no assumptions about time zones. However, it can only support dates, not times:

dt <- "2021-04-15 13:20:00"

as.Date(dt)
## [1] "2021-04-15"

When we convert a date-time string into Date, the time information is lost.

What if our date was in a different format than “2021-04-15”?

as.Date("04/15/2021")
## Error in charToDate(x): character string is not in a standard unambiguous format
as.POSIXct("04/15/2021")
## Error in as.POSIXlt.character(x, tz, ...): character string is not in a standard unambiguous format
as.POSIXlt("04/15/2021")
## Error in as.POSIXlt.character("04/15/2021"): character string is not in a standard unambiguous format

None of the functions above work because they can’t understand the format of the date. To make this work, we would have to give R a template of how the object is formatted. In our case, the format is “month/day/4-digit year” which is encoded as %m/%d/%Y:

as.Date("04/15/2021", format = "%m/%d/%Y")
## [1] "2021-04-15"
as.POSIXct("04/15/2021", format = "%m/%d/%Y")
## [1] "2021-04-15 MDT"
as.POSIXlt("04/15/2021", format = "%m/%d/%Y")
## [1] "2021-04-15 MDT"

What happens if we want to do some calculations on dates? For example, we want to know how many days went by between two dates. If our dates are formatted using a different data type, we may get some unexpected results:

d1 <- as.POSIXct("2021-04-15")
d2 <- as.POSIXlt("2021-04-16")
d3 <- as.Date("2021-04-17")

d3 - d1
## Warning: Incompatible methods ("-.Date", "-.POSIXt") for "-"
## [1] "-4429190-10-18"
d2 - d3
## Warning: Incompatible methods ("-.POSIXt", "-.Date") for "-"
## Error in d2 - d3: non-numeric argument to binary operator
d3 - d1
## Warning: Incompatible methods ("-.Date", "-.POSIXt") for "-"
## [1] "-4429190-10-18"
d1 - d2
## Time difference of -1 days
d1 - d3
## Warning: Incompatible methods ("-.POSIXt", "-.Date") for "-"
## [1] "2021-04-14 18:47:46 MDT"

Only one of the calculations above (d1 - d2, where we are subtracting a POSIXlt from a POSIXct) worked and returned the right output. All the other ones returned weird outputs and a warning that the methods are incompatible.

The ones above are just a few examples to demonstrate how working with dates and times in R can still be complicated even using dedicated data types available within base R.

15.4 The lubridate package

Artwork by Allison Horst

Figure 15.1: Artwork by Allison Horst

Working with dates and times in R becomes a whole lot easier when using the lubridate package. lubridate is part of the tidyverse and it is meant to make working with dates and time as straightforward as possible. For one, functions in lubridate are designed to behave consistently regardless of the underlying object. No need to keep track of what functions we can or cannot use on different date-time objects: the same handful of function work predictably on all of them. Using lubridate does not mean foregoing base R’s handling of date-time objects: the package works nicely with built-in objects, it just makes them more user-friendly. Let’s look at some of the functionalities of lubridate.

library(lubridate)
## Warning: package 'lubridate' was built under R version 4.0.3

15.4.1 Parsing dates and times

lubridate comes with a suite of different functions to parse (i.e., correctly interpret the components of) dates, times, and timestamp. These functions are:

ymd()
mdy()
dmy()

ymd_hms()
mdy_hms()
dmy_hms()

hms()
hm()
ms()

Depending on what format our input data is in, all we need to do is pick the correct function to convert our string into a date-time object:

# This string follows the format "year, month, day", so we use ymd()
ymd("2021-04-15")
## [1] "2021-04-15"
# Separator doesn't matter! And neither do leading zeros.
ymd("2021/4/15")
## [1] "2021-04-15"
# This string follows the format "month, day, year", so we use mdy()
mdy("4/15/2021")
## [1] "2021-04-15"

Note that all of these functions return the same identical output: the output format is always yyyy-mm-dd and the output data type is always Date.

class(ymd("2021-04-15"))
## [1] "Date"
class(ymd("2021/4/15"))
## [1] "Date"
class(mdy("4/15/2021"))
## [1] "Date"

Let’s try with some timestamps:

# This string follows the format "year, month, day, hour, minute, second", 
# so we use ymd_hms()
ymd_hms("2021-04-15 13:53:00")
## [1] "2021-04-15 13:53:00 UTC"
# Separator doesn't matter! 
ymd_hms("2021/4/15 13 53 00")
## [1] "2021-04-15 13:53:00 UTC"
# This string follows the format "month, day, year, hour, minute", so we use mdy_hm()
mdy_hm("4/15/2021 13:53")
## [1] "2021-04-15 13:53:00 UTC"

Again, the output format is always the same and the output class is too (this time it’s POSIXct because there’s a time component in addition to the date):

class(ymd_hms("2021-04-15 13:53:00"))
## [1] "POSIXct" "POSIXt"
class(ymd_hms("2021/4/15 13 53 00"))
## [1] "POSIXct" "POSIXt"
class(mdy_hm("4/15/2021 13:53"))
## [1] "POSIXct" "POSIXt"

What happens if we use a function that doesn’t match the format we are providing in input?

ymd("2021-04-15 13:56:00")
## Warning: All formats failed to parse. No formats found.
## [1] NA

The output is NA and we get a warning that the date failed to parse. That is because ymd() is expecting a year, a month, and a day only; instead, we are giving it a full timestamp (year, month, day, hour, minute, second).

ymd_hms("04/15/2021 13:56:00")
## Warning: All formats failed to parse. No formats found.
## [1] NA

This one failed because ymd_hms() is expecting the elements in this order: year, month, day, hour, minute, second, but we are giving it in a different order (month, day, year, hour, minute, second). So, whenever you get the warning, All formats failed to parse. No formats found. you’ll know that you either passed more components than the function expected, fewer components than the function expected, or you passed them in the wrong order.

One misconception that I frequently see is that people tend to think that the different functions we’ve seen (ymd(), mdy(), dmy(), etc.) are used to tell lubridate what format we want in output; but actually, the output returned is always the same. Those different functions exist so that can choose the appropriate function to match the format of our input, so that the string can be parsed correctly.

15.4.2 Extracting components of a date-time object

The following functions in lubridate let you extract components of a date-time object:

dt <- mdy_hms("04/15/2021 13:56:00")

day(dt)
## [1] 15
month(dt)
## [1] 4
year(dt)
## [1] 2021
hour(dt)
## [1] 13
minute(dt)
## [1] 56
second(dt)
## [1] 0

15.4.3 Time zones

By default, when we create a new timestamp with lubridate, it will be assumed to be in UTC (Coordinated Universal Time):

ymd_hms("2021-04-15 13:56:00")
## [1] "2021-04-15 13:56:00 UTC"

What if the timestamp is actually in a different time zone than that? We can use the argument tz to specify what time zone the data are in when we create the object. For a list of available time zones, we can look up:

OlsonNames()
##   [1] "Africa/Abidjan"                   "Africa/Accra"                    
##   [3] "Africa/Addis_Ababa"               "Africa/Algiers"                  
##   [5] "Africa/Asmara"                    "Africa/Asmera"                   
##   [7] "Africa/Bamako"                    "Africa/Bangui"                   
##   [9] "Africa/Banjul"                    "Africa/Bissau"                   
##  [11] "Africa/Blantyre"                  "Africa/Brazzaville"              
##  [13] "Africa/Bujumbura"                 "Africa/Cairo"                    
##  [15] "Africa/Casablanca"                "Africa/Ceuta"                    
##  [17] "Africa/Conakry"                   "Africa/Dakar"                    
##  [19] "Africa/Dar_es_Salaam"             "Africa/Djibouti"                 
##  [21] "Africa/Douala"                    "Africa/El_Aaiun"                 
##  [23] "Africa/Freetown"                  "Africa/Gaborone"                 
##  [25] "Africa/Harare"                    "Africa/Johannesburg"             
##  [27] "Africa/Juba"                      "Africa/Kampala"                  
##  [29] "Africa/Khartoum"                  "Africa/Kigali"                   
##  [31] "Africa/Kinshasa"                  "Africa/Lagos"                    
##  [33] "Africa/Libreville"                "Africa/Lome"                     
##  [35] "Africa/Luanda"                    "Africa/Lubumbashi"               
##  [37] "Africa/Lusaka"                    "Africa/Malabo"                   
##  [39] "Africa/Maputo"                    "Africa/Maseru"                   
##  [41] "Africa/Mbabane"                   "Africa/Mogadishu"                
##  [43] "Africa/Monrovia"                  "Africa/Nairobi"                  
##  [45] "Africa/Ndjamena"                  "Africa/Niamey"                   
##  [47] "Africa/Nouakchott"                "Africa/Ouagadougou"              
##  [49] "Africa/Porto-Novo"                "Africa/Sao_Tome"                 
##  [51] "Africa/Timbuktu"                  "Africa/Tripoli"                  
##  [53] "Africa/Tunis"                     "Africa/Windhoek"                 
##  [55] "America/Adak"                     "America/Anchorage"               
##  [57] "America/Anguilla"                 "America/Antigua"                 
##  [59] "America/Araguaina"                "America/Argentina/Buenos_Aires"  
##  [61] "America/Argentina/Catamarca"      "America/Argentina/ComodRivadavia"
##  [63] "America/Argentina/Cordoba"        "America/Argentina/Jujuy"         
##  [65] "America/Argentina/La_Rioja"       "America/Argentina/Mendoza"       
##  [67] "America/Argentina/Rio_Gallegos"   "America/Argentina/Salta"         
##  [69] "America/Argentina/San_Juan"       "America/Argentina/San_Luis"      
##  [71] "America/Argentina/Tucuman"        "America/Argentina/Ushuaia"       
##  [73] "America/Aruba"                    "America/Asuncion"                
##  [75] "America/Atikokan"                 "America/Atka"                    
##  [77] "America/Bahia"                    "America/Bahia_Banderas"          
##  [79] "America/Barbados"                 "America/Belem"                   
##  [81] "America/Belize"                   "America/Blanc-Sablon"            
##  [83] "America/Boa_Vista"                "America/Bogota"                  
##  [85] "America/Boise"                    "America/Buenos_Aires"            
##  [87] "America/Cambridge_Bay"            "America/Campo_Grande"            
##  [89] "America/Cancun"                   "America/Caracas"                 
##  [91] "America/Catamarca"                "America/Cayenne"                 
##  [93] "America/Cayman"                   "America/Chicago"                 
##  [95] "America/Chihuahua"                "America/Coral_Harbour"           
##  [97] "America/Cordoba"                  "America/Costa_Rica"              
##  [99] "America/Creston"                  "America/Cuiaba"                  
## [101] "America/Curacao"                  "America/Danmarkshavn"            
## [103] "America/Dawson"                   "America/Dawson_Creek"            
## [105] "America/Denver"                   "America/Detroit"                 
## [107] "America/Dominica"                 "America/Edmonton"                
## [109] "America/Eirunepe"                 "America/El_Salvador"             
## [111] "America/Ensenada"                 "America/Fort_Nelson"             
## [113] "America/Fort_Wayne"               "America/Fortaleza"               
## [115] "America/Glace_Bay"                "America/Godthab"                 
## [117] "America/Goose_Bay"                "America/Grand_Turk"              
## [119] "America/Grenada"                  "America/Guadeloupe"              
## [121] "America/Guatemala"                "America/Guayaquil"               
## [123] "America/Guyana"                   "America/Halifax"                 
## [125] "America/Havana"                   "America/Hermosillo"              
## [127] "America/Indiana/Indianapolis"     "America/Indiana/Knox"            
## [129] "America/Indiana/Marengo"          "America/Indiana/Petersburg"      
## [131] "America/Indiana/Tell_City"        "America/Indiana/Vevay"           
## [133] "America/Indiana/Vincennes"        "America/Indiana/Winamac"         
## [135] "America/Indianapolis"             "America/Inuvik"                  
## [137] "America/Iqaluit"                  "America/Jamaica"                 
## [139] "America/Jujuy"                    "America/Juneau"                  
## [141] "America/Kentucky/Louisville"      "America/Kentucky/Monticello"     
## [143] "America/Knox_IN"                  "America/Kralendijk"              
## [145] "America/La_Paz"                   "America/Lima"                    
## [147] "America/Los_Angeles"              "America/Louisville"              
## [149] "America/Lower_Princes"            "America/Maceio"                  
## [151] "America/Managua"                  "America/Manaus"                  
## [153] "America/Marigot"                  "America/Martinique"              
## [155] "America/Matamoros"                "America/Mazatlan"                
## [157] "America/Mendoza"                  "America/Menominee"               
## [159] "America/Merida"                   "America/Metlakatla"              
## [161] "America/Mexico_City"              "America/Miquelon"                
## [163] "America/Moncton"                  "America/Monterrey"               
## [165] "America/Montevideo"               "America/Montreal"                
## [167] "America/Montserrat"               "America/Nassau"                  
## [169] "America/New_York"                 "America/Nipigon"                 
## [171] "America/Nome"                     "America/Noronha"                 
## [173] "America/North_Dakota/Beulah"      "America/North_Dakota/Center"     
## [175] "America/North_Dakota/New_Salem"   "America/Nuuk"                    
## [177] "America/Ojinaga"                  "America/Panama"                  
## [179] "America/Pangnirtung"              "America/Paramaribo"              
## [181] "America/Phoenix"                  "America/Port-au-Prince"          
## [183] "America/Port_of_Spain"            "America/Porto_Acre"              
## [185] "America/Porto_Velho"              "America/Puerto_Rico"             
## [187] "America/Punta_Arenas"             "America/Rainy_River"             
## [189] "America/Rankin_Inlet"             "America/Recife"                  
## [191] "America/Regina"                   "America/Resolute"                
## [193] "America/Rio_Branco"               "America/Rosario"                 
## [195] "America/Santa_Isabel"             "America/Santarem"                
## [197] "America/Santiago"                 "America/Santo_Domingo"           
## [199] "America/Sao_Paulo"                "America/Scoresbysund"            
## [201] "America/Shiprock"                 "America/Sitka"                   
## [203] "America/St_Barthelemy"            "America/St_Johns"                
## [205] "America/St_Kitts"                 "America/St_Lucia"                
## [207] "America/St_Thomas"                "America/St_Vincent"              
## [209] "America/Swift_Current"            "America/Tegucigalpa"             
## [211] "America/Thule"                    "America/Thunder_Bay"             
## [213] "America/Tijuana"                  "America/Toronto"                 
## [215] "America/Tortola"                  "America/Vancouver"               
## [217] "America/Virgin"                   "America/Whitehorse"              
## [219] "America/Winnipeg"                 "America/Yakutat"                 
## [221] "America/Yellowknife"              "Antarctica/Casey"                
## [223] "Antarctica/Davis"                 "Antarctica/DumontDUrville"       
## [225] "Antarctica/Macquarie"             "Antarctica/Mawson"               
## [227] "Antarctica/McMurdo"               "Antarctica/Palmer"               
## [229] "Antarctica/Rothera"               "Antarctica/South_Pole"           
## [231] "Antarctica/Syowa"                 "Antarctica/Troll"                
## [233] "Antarctica/Vostok"                "Arctic/Longyearbyen"             
## [235] "Asia/Aden"                        "Asia/Almaty"                     
## [237] "Asia/Amman"                       "Asia/Anadyr"                     
## [239] "Asia/Aqtau"                       "Asia/Aqtobe"                     
## [241] "Asia/Ashgabat"                    "Asia/Ashkhabad"                  
## [243] "Asia/Atyrau"                      "Asia/Baghdad"                    
## [245] "Asia/Bahrain"                     "Asia/Baku"                       
## [247] "Asia/Bangkok"                     "Asia/Barnaul"                    
## [249] "Asia/Beirut"                      "Asia/Bishkek"                    
## [251] "Asia/Brunei"                      "Asia/Calcutta"                   
## [253] "Asia/Chita"                       "Asia/Choibalsan"                 
## [255] "Asia/Chongqing"                   "Asia/Chungking"                  
## [257] "Asia/Colombo"                     "Asia/Dacca"                      
## [259] "Asia/Damascus"                    "Asia/Dhaka"                      
## [261] "Asia/Dili"                        "Asia/Dubai"                      
## [263] "Asia/Dushanbe"                    "Asia/Famagusta"                  
## [265] "Asia/Gaza"                        "Asia/Harbin"                     
## [267] "Asia/Hebron"                      "Asia/Ho_Chi_Minh"                
## [269] "Asia/Hong_Kong"                   "Asia/Hovd"                       
## [271] "Asia/Irkutsk"                     "Asia/Istanbul"                   
## [273] "Asia/Jakarta"                     "Asia/Jayapura"                   
## [275] "Asia/Jerusalem"                   "Asia/Kabul"                      
## [277] "Asia/Kamchatka"                   "Asia/Karachi"                    
## [279] "Asia/Kashgar"                     "Asia/Kathmandu"                  
## [281] "Asia/Katmandu"                    "Asia/Khandyga"                   
## [283] "Asia/Kolkata"                     "Asia/Krasnoyarsk"                
## [285] "Asia/Kuala_Lumpur"                "Asia/Kuching"                    
## [287] "Asia/Kuwait"                      "Asia/Macao"                      
## [289] "Asia/Macau"                       "Asia/Magadan"                    
## [291] "Asia/Makassar"                    "Asia/Manila"                     
## [293] "Asia/Muscat"                      "Asia/Nicosia"                    
## [295] "Asia/Novokuznetsk"                "Asia/Novosibirsk"                
## [297] "Asia/Omsk"                        "Asia/Oral"                       
## [299] "Asia/Phnom_Penh"                  "Asia/Pontianak"                  
## [301] "Asia/Pyongyang"                   "Asia/Qatar"                      
## [303] "Asia/Qostanay"                    "Asia/Qyzylorda"                  
## [305] "Asia/Rangoon"                     "Asia/Riyadh"                     
## [307] "Asia/Saigon"                      "Asia/Sakhalin"                   
## [309] "Asia/Samarkand"                   "Asia/Seoul"                      
## [311] "Asia/Shanghai"                    "Asia/Singapore"                  
## [313] "Asia/Srednekolymsk"               "Asia/Taipei"                     
## [315] "Asia/Tashkent"                    "Asia/Tbilisi"                    
## [317] "Asia/Tehran"                      "Asia/Tel_Aviv"                   
## [319] "Asia/Thimbu"                      "Asia/Thimphu"                    
## [321] "Asia/Tokyo"                       "Asia/Tomsk"                      
## [323] "Asia/Ujung_Pandang"               "Asia/Ulaanbaatar"                
## [325] "Asia/Ulan_Bator"                  "Asia/Urumqi"                     
## [327] "Asia/Ust-Nera"                    "Asia/Vientiane"                  
## [329] "Asia/Vladivostok"                 "Asia/Yakutsk"                    
## [331] "Asia/Yangon"                      "Asia/Yekaterinburg"              
## [333] "Asia/Yerevan"                     "Atlantic/Azores"                 
## [335] "Atlantic/Bermuda"                 "Atlantic/Canary"                 
## [337] "Atlantic/Cape_Verde"              "Atlantic/Faeroe"                 
## [339] "Atlantic/Faroe"                   "Atlantic/Jan_Mayen"              
## [341] "Atlantic/Madeira"                 "Atlantic/Reykjavik"              
## [343] "Atlantic/South_Georgia"           "Atlantic/St_Helena"              
## [345] "Atlantic/Stanley"                 "Australia/ACT"                   
## [347] "Australia/Adelaide"               "Australia/Brisbane"              
## [349] "Australia/Broken_Hill"            "Australia/Canberra"              
## [351] "Australia/Currie"                 "Australia/Darwin"                
## [353] "Australia/Eucla"                  "Australia/Hobart"                
## [355] "Australia/LHI"                    "Australia/Lindeman"              
## [357] "Australia/Lord_Howe"              "Australia/Melbourne"             
## [359] "Australia/North"                  "Australia/NSW"                   
## [361] "Australia/Perth"                  "Australia/Queensland"            
## [363] "Australia/South"                  "Australia/Sydney"                
## [365] "Australia/Tasmania"               "Australia/Victoria"              
## [367] "Australia/West"                   "Australia/Yancowinna"            
## [369] "Brazil/Acre"                      "Brazil/DeNoronha"                
## [371] "Brazil/East"                      "Brazil/West"                     
## [373] "Canada/Atlantic"                  "Canada/Central"                  
## [375] "Canada/Eastern"                   "Canada/Mountain"                 
## [377] "Canada/Newfoundland"              "Canada/Pacific"                  
## [379] "Canada/Saskatchewan"              "Canada/Yukon"                    
## [381] "CET"                              "Chile/Continental"               
## [383] "Chile/EasterIsland"               "CST6CDT"                         
## [385] "Cuba"                             "EET"                             
## [387] "Egypt"                            "Eire"                            
## [389] "EST"                              "EST5EDT"                         
## [391] "Etc/GMT"                          "Etc/GMT-0"                       
## [393] "Etc/GMT-1"                        "Etc/GMT-10"                      
## [395] "Etc/GMT-11"                       "Etc/GMT-12"                      
## [397] "Etc/GMT-13"                       "Etc/GMT-14"                      
## [399] "Etc/GMT-2"                        "Etc/GMT-3"                       
## [401] "Etc/GMT-4"                        "Etc/GMT-5"                       
## [403] "Etc/GMT-6"                        "Etc/GMT-7"                       
## [405] "Etc/GMT-8"                        "Etc/GMT-9"                       
## [407] "Etc/GMT+0"                        "Etc/GMT+1"                       
## [409] "Etc/GMT+10"                       "Etc/GMT+11"                      
## [411] "Etc/GMT+12"                       "Etc/GMT+2"                       
## [413] "Etc/GMT+3"                        "Etc/GMT+4"                       
## [415] "Etc/GMT+5"                        "Etc/GMT+6"                       
## [417] "Etc/GMT+7"                        "Etc/GMT+8"                       
## [419] "Etc/GMT+9"                        "Etc/GMT0"                        
## [421] "Etc/Greenwich"                    "Etc/UCT"                         
## [423] "Etc/Universal"                    "Etc/UTC"                         
## [425] "Etc/Zulu"                         "Europe/Amsterdam"                
## [427] "Europe/Andorra"                   "Europe/Astrakhan"                
## [429] "Europe/Athens"                    "Europe/Belfast"                  
## [431] "Europe/Belgrade"                  "Europe/Berlin"                   
## [433] "Europe/Bratislava"                "Europe/Brussels"                 
## [435] "Europe/Bucharest"                 "Europe/Budapest"                 
## [437] "Europe/Busingen"                  "Europe/Chisinau"                 
## [439] "Europe/Copenhagen"                "Europe/Dublin"                   
## [441] "Europe/Gibraltar"                 "Europe/Guernsey"                 
## [443] "Europe/Helsinki"                  "Europe/Isle_of_Man"              
## [445] "Europe/Istanbul"                  "Europe/Jersey"                   
## [447] "Europe/Kaliningrad"               "Europe/Kiev"                     
## [449] "Europe/Kirov"                     "Europe/Lisbon"                   
## [451] "Europe/Ljubljana"                 "Europe/London"                   
## [453] "Europe/Luxembourg"                "Europe/Madrid"                   
## [455] "Europe/Malta"                     "Europe/Mariehamn"                
## [457] "Europe/Minsk"                     "Europe/Monaco"                   
## [459] "Europe/Moscow"                    "Europe/Nicosia"                  
## [461] "Europe/Oslo"                      "Europe/Paris"                    
## [463] "Europe/Podgorica"                 "Europe/Prague"                   
## [465] "Europe/Riga"                      "Europe/Rome"                     
## [467] "Europe/Samara"                    "Europe/San_Marino"               
## [469] "Europe/Sarajevo"                  "Europe/Saratov"                  
## [471] "Europe/Simferopol"                "Europe/Skopje"                   
## [473] "Europe/Sofia"                     "Europe/Stockholm"                
## [475] "Europe/Tallinn"                   "Europe/Tirane"                   
## [477] "Europe/Tiraspol"                  "Europe/Ulyanovsk"                
## [479] "Europe/Uzhgorod"                  "Europe/Vaduz"                    
## [481] "Europe/Vatican"                   "Europe/Vienna"                   
## [483] "Europe/Vilnius"                   "Europe/Volgograd"                
## [485] "Europe/Warsaw"                    "Europe/Zagreb"                   
## [487] "Europe/Zaporozhye"                "Europe/Zurich"                   
## [489] "GB"                               "GB-Eire"                         
## [491] "GMT"                              "GMT-0"                           
## [493] "GMT+0"                            "GMT0"                            
## [495] "Greenwich"                        "Hongkong"                        
## [497] "HST"                              "Iceland"                         
## [499] "Indian/Antananarivo"              "Indian/Chagos"                   
## [501] "Indian/Christmas"                 "Indian/Cocos"                    
## [503] "Indian/Comoro"                    "Indian/Kerguelen"                
## [505] "Indian/Mahe"                      "Indian/Maldives"                 
## [507] "Indian/Mauritius"                 "Indian/Mayotte"                  
## [509] "Indian/Reunion"                   "Iran"                            
## [511] "Israel"                           "Jamaica"                         
## [513] "Japan"                            "Kwajalein"                       
## [515] "Libya"                            "MET"                             
## [517] "Mexico/BajaNorte"                 "Mexico/BajaSur"                  
## [519] "Mexico/General"                   "MST"                             
## [521] "MST7MDT"                          "Navajo"                          
## [523] "NZ"                               "NZ-CHAT"                         
## [525] "Pacific/Apia"                     "Pacific/Auckland"                
## [527] "Pacific/Bougainville"             "Pacific/Chatham"                 
## [529] "Pacific/Chuuk"                    "Pacific/Easter"                  
## [531] "Pacific/Efate"                    "Pacific/Enderbury"               
## [533] "Pacific/Fakaofo"                  "Pacific/Fiji"                    
## [535] "Pacific/Funafuti"                 "Pacific/Galapagos"               
## [537] "Pacific/Gambier"                  "Pacific/Guadalcanal"             
## [539] "Pacific/Guam"                     "Pacific/Honolulu"                
## [541] "Pacific/Johnston"                 "Pacific/Kiritimati"              
## [543] "Pacific/Kosrae"                   "Pacific/Kwajalein"               
## [545] "Pacific/Majuro"                   "Pacific/Marquesas"               
## [547] "Pacific/Midway"                   "Pacific/Nauru"                   
## [549] "Pacific/Niue"                     "Pacific/Norfolk"                 
## [551] "Pacific/Noumea"                   "Pacific/Pago_Pago"               
## [553] "Pacific/Palau"                    "Pacific/Pitcairn"                
## [555] "Pacific/Pohnpei"                  "Pacific/Ponape"                  
## [557] "Pacific/Port_Moresby"             "Pacific/Rarotonga"               
## [559] "Pacific/Saipan"                   "Pacific/Samoa"                   
## [561] "Pacific/Tahiti"                   "Pacific/Tarawa"                  
## [563] "Pacific/Tongatapu"                "Pacific/Truk"                    
## [565] "Pacific/Wake"                     "Pacific/Wallis"                  
## [567] "Pacific/Yap"                      "Poland"                          
## [569] "Portugal"                         "PRC"                             
## [571] "PST8PDT"                          "ROC"                             
## [573] "ROK"                              "Singapore"                       
## [575] "Turkey"                           "UCT"                             
## [577] "Universal"                        "US/Alaska"                       
## [579] "US/Aleutian"                      "US/Arizona"                      
## [581] "US/Central"                       "US/East-Indiana"                 
## [583] "US/Eastern"                       "US/Hawaii"                       
## [585] "US/Indiana-Starke"                "US/Michigan"                     
## [587] "US/Mountain"                      "US/Pacific"                      
## [589] "US/Pacific-New"                   "US/Samoa"                        
## [591] "UTC"                              "W-SU"                            
## [593] "WET"                              "Zulu"                            
## attr(,"Version")
## [1] "2020a"

Our time zone is “America/Denver”. Let’s specify that when creating our object:

dt <- ymd_hms("2021-04-15 13:56:00", tz = "America/Denver")

dt
## [1] "2021-04-15 13:56:00 MDT"

Notice that lubridate knows that 2021-04-15 is during Daylight Savings Time, and it automatically assigns MDT instead of MST.

Now we can convert this object in whichever time zone we want. For instance, when it’s 13:56:00 in Logan, UT on April 15th 2021, what time is it in Rome, Italy?

with_tz(dt, tz = "Europe/Rome")
## [1] "2021-04-15 21:56:00 CEST"

And what time is that in New York City?

with_tz(dt, tz = "America/New_York")
## [1] "2021-04-15 15:56:00 EDT"

What if we didn’t mean to get the equivalent of “2021-04-15 13:56:00 MDT” in another time zone, but instead we wanted to keep the timestamp exactly as it is but set it in a different time zone? We can use force_tz():

dt
## [1] "2021-04-15 13:56:00 MDT"
force_tz(dt, tz = "America/New_York")
## [1] "2021-04-15 13:56:00 EDT"

15.4.4 Time spans

lubridate works with three types of time spans:

  • Periods are fixed amounts of time, ignoring any time irregularities;
  • Durations are amounts of time that account for time irregularities such as leap years or months of different length;
  • Intervals are stretches of time between a specific start date and end date.

Let’s look at a few examples to illustrate the difference between these. For example, we can get a period of N months by using the function months(), and a duration of N months by using the function dmonths():

class(months(2))
## [1] "Period"
## attr(,"package")
## [1] "lubridate"
class(dmonths(2))
## [1] "Duration"
## attr(,"package")
## [1] "lubridate"
dt + months(2)
## [1] "2021-06-15 13:56:00 MDT"
dt + dmonths(2)
## [1] "2021-06-15 10:56:00 MDT"

Our dt timestamp is in April. Adding a period of 2 months to dt means simply changing the month component to June, leaving everything else unchanged. Adding a duration of 2 months to dt means adding the average equivalent of 2 months in seconds (not all months have the same amount of seconds in them because the duration of a month changes between 28 and 31 days, so that’s why I specified “average”). That’s why the result when we add a 2-month duration to dt is 3 hours earlier than when we add a 2-month period.

Periods and durations are useful for doing math with date-time objects. We can answer questions such as, what time will it be in 1 hour and 30 minutes?

dt + hours(1) + minutes(30)
## [1] "2021-04-15 15:26:00 MDT"

Or, say that we want to know what day of the week it was today, 3 years ago:

dt_minus3y <- dt - years(3)

wday(dt_minus3y, label = TRUE) # wday() returns the day of the week
## [1] Sun
## Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat

Three years ago today was Sunday!

Unlike periods and durations, intervals are especially handy for some type of operations where it matters when exactly a time span takes place (not just how long it is). For example, say that we have a period that goes from January 19th, 2021 (our first class this semester) to April 27th, 2021 (our last class this semester):

# There are two equivalent ways to create an interval: 

# Option 1
s <- interval(ymd("2021-01-19", tz = "America/Denver"), ymd("2021-04-27", tz = "America/Denver"))

# Option 2
s <- ymd("2021-01-19", tz = "America/Denver") %--% ymd("2021-04-27", tz = "America/Denver")

class(s)
## [1] "Interval"
## attr(,"package")
## [1] "lubridate"

We can get the start or end date of an interval as follows:

int_start(s)
## [1] "2021-01-19 MST"
int_end(s)
## [1] "2021-04-27 MDT"

We can check how long the interval is:

int_length(s) # default output is in seconds
## [1] 8463600

We can check if any arbitrary date falls within that interval:

ymd("2021-03-14") %within% s
## [1] TRUE
ymd("1998-03-14") %within% s
## [1] FALSE

We can shift the interval up or down by a certain time span:

int_shift(s, by = months(1)) # push back by one month
## [1] 2021-02-19 MST--2021-05-27 MDT
int_shift(s, by = days(-7)) # bring forward by one week
## [1] 2021-01-12 MST--2021-04-20 MDT

We can create multiple intervals and check whether they overlap:

i <- interval(ymd("2017-07-24", tz = "America/Denver"), ymd("2021-02-12", tz = "America/Denver"))

int_overlaps(i, s)
## [1] TRUE

15.5 References