Dates And Times

2024-09-30

Parsing dates and times

  • We have described three main types of vectors: numeric, character, and logical.

  • When analyzing data, we often encounter variables that are dates.

  • Although we can represent a date with a string, for example November 2, 2017, once we pick a reference day, referred to as the epoch by computer programmers, they can be converted to numbers by calculating the number of days since the epoch.

  • In R and Unix, the epoch is defined as January 1, 1970.

Parsing dates and times

  • If I tell you it’s November 2, 2017, you know what this means immediately.

  • If I tell you it’s day 17,204, you will be quite confused.

  • Similar problems arise with times and even more complications can appear due to time zones.

  • For this reason, R defines a data type just for dates and times.

The date data type

  • We can see an example of the data type R uses for data here:
library(tidyverse) 
library(dslabs) 
polls_us_election_2016$startdate |> head() 
[1] "2016-11-03" "2016-11-01" "2016-11-02" "2016-11-04" "2016-11-03"
[6] "2016-11-03"
  • The dates look like strings, but they are not:
class(polls_us_election_2016$startdate) 
[1] "Date"

The date data type

  • Look at what happens when we convert them to numbers:
as.numeric(polls_us_election_2016$startdate) |> head() 
[1] 17108 17106 17107 17109 17108 17108
  • It turns them into days since the epoch.

The date data type

  • as.Date converts characters into dates.

  • So to see that the epoch is day 0 we can type.

as.Date("1970-01-01") |> as.numeric() 
[1] 0
  • Plotting functions, such as those in ggplot, are aware of the date format.

The date data type

  • Scatterplots use the numeric representation to assign positions, but include the string in the labels:
polls_us_election_2016 |> 
  filter(startdate >= make_date(2016, 6, 1)) |>
  filter(pollster == "Ipsos" & state == "U.S.") |> 
  ggplot(aes(startdate, rawpoll_clinton)) + 
  geom_line() 

The date data type

ggplot offers convenient functions to change labels:

polls_us_election_2016 |> 
  filter(startdate >= make_date(2016, 6, 1)) |>
  filter(pollster == "Ipsos" & state == "U.S.") |> 
  ggplot(aes(startdate, rawpoll_clinton)) + 
  geom_line() +
  scale_x_date(date_breaks = "2 weeks", date_labels = "%b %d") + 
  geom_vline(xintercept = as.Date("2016-10-28"), linetype = "dashed")

The lubridate package

  • The lubridate package provides tools to work with date and times.
library(lubridate) 
  • We will take a random sample of dates to show some of the useful things one can do:
set.seed(2002) 
dates <- sample(polls_us_election_2016$startdate, 10) |> sort() 
dates 
 [1] "2016-05-31" "2016-08-08" "2016-08-19" "2016-09-22" "2016-09-27"
 [6] "2016-10-12" "2016-10-24" "2016-10-26" "2016-10-29" "2016-10-30"

The lubridate package

  • The functions year, month and day extract those values:
tibble(date = dates, month = month(dates), day = day(dates), year = year(dates)) 
# A tibble: 10 × 4
   date       month   day  year
   <date>     <dbl> <int> <dbl>
 1 2016-05-31     5    31  2016
 2 2016-08-08     8     8  2016
 3 2016-08-19     8    19  2016
 4 2016-09-22     9    22  2016
 5 2016-09-27     9    27  2016
 6 2016-10-12    10    12  2016
 7 2016-10-24    10    24  2016
 8 2016-10-26    10    26  2016
 9 2016-10-29    10    29  2016
10 2016-10-30    10    30  2016

The lubridate package

  • We can also extract the month labels:
month(dates, label = TRUE) 
 [1] May Aug Aug Sep Sep Oct Oct Oct Oct Oct
12 Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < ... < Dec

The lubridate package

  • Another useful set of functions are the parsers that convert strings into dates.

  • The function ymd assumes the dates are in the format YYYY-MM-DD and tries to parse as well as possible.

x <- c(20090101, "2009-01-02", "2009 01 03", "2009-1-4", 
       "2009-1, 5", "Created on 2009 1 6", "200901 !!! 07") 
ymd(x) 
[1] "2009-01-01" "2009-01-02" "2009-01-03" "2009-01-04" "2009-01-05"
[6] "2009-01-06" "2009-01-07"

The lubridate package

  • A further complication comes from the fact that dates often come in different formats in which the order of year, month, and day are different.

  • The preferred format is to show year (with all four digits), month (two digits), and then day, or what is called the ISO 8601.

  • Specifically we use YYYY-MM-DD so that if we order the string, it will be ordered by date.

  • You can see the function ymd returns them in this format.

The lubridate package

  • But, what if you encounter dates such as “09/01/02”? This could be September 1, 2002 or January 2, 2009 or January 9, 2002.

  • In these cases, examining the entire vector of dates will help you determine what format it is by process of elimination.

  • Once you know, you can use the many parses provided by lubridate.

  • For example, if the string is:

x <- "09/01/02" 

The lubridate package

  • The ymd function assumes the first entry is the year, the second is the month, and the third is the day, so it converts it to:
ymd(x) 
[1] "2009-01-02"

The lubridate package

  • The mdy function assumes the first entry is the month, then the day, then the year:
mdy(x) 
[1] "2002-09-01"

The lubridate package

  • The lubridate package provides a function for every possibility.

  • Here is the other common one:

dmy(x) 
[1] "2002-01-09"

The lubridate package

  • The lubridate package is also useful for dealing with times.

  • In base R, you can get the current time typing Sys.time().

  • The lubridate package provides a slightly more advanced function, now, that permits you to define the time zone:

now() 
[1] "2024-10-27 22:42:35 EDT"
now("GMT") 
[1] "2024-10-28 02:42:35 GMT"

The lubridate package

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

The lubridate package

  • We can also extract hours, minutes, and seconds:
now() |> hour() 
[1] 22
now() |> minute() 
[1] 42
now() |> second() 
[1] 35.90475

The lubridate package

  • The package also includes a function to parse strings into times as well as parsers for time objects that include dates:
x <- c("12:34:56") 
hms(x) 
[1] "12H 34M 56S"
x <- "Nov/2/2012 12:34:56" 
mdy_hms(x) 
[1] "2012-11-02 12:34:56 UTC"

The lubridate package

  • The make_date function can be used to quickly create a date object.

  • For example, to create an date object representing, for example, July 6, 2019 we write:

make_date(2019, 7, 6) 
[1] "2019-07-06"

The lubridate package

  • We can use it to make vectors of dates.

  • To make a vector of January 1 for the 80s we write:

make_date(1980:1989) 
 [1] "1980-01-01" "1981-01-01" "1982-01-01" "1983-01-01" "1984-01-01"
 [6] "1985-01-01" "1986-01-01" "1987-01-01" "1988-01-01" "1989-01-01"

The lubridate package

  • Another very useful function is round_date.

  • It can be used to round dates to nearest year, quarter, month, week, day, hour, minutes, or seconds.

The lubridate package

  • Example: if we want to group all the polls by week of the year we can do the following:
polls_us_election_2016 |>  
  mutate(week = round_date(startdate, "week")) |> 
  group_by(week) |> 
  summarize(margin = mean(rawpoll_clinton - rawpoll_trump)) |> 
  ggplot(aes(week, margin)) + 
  geom_point() 

Final pointers

  • You should be aware the there are useful function for computing operations on time such a difftime, time_length, and interval.

  • We don’t cover it here but be aware that The data.table package includes some of the same functionality as lubridate.