Formatting dates in R

Manipulating Time Series Data in R

Harrison Brown

Graduate Researcher in Geography

Order of time elements

Order of day, month, and year:

  • U.S.: 12/20/2022
  • U.K.: 20/12/2022
  • Ambiguous most of the year:
    • 6/4/2010: June 4th or April 6th?

 

"Time elements":

  • Day, Month, Year
  • Hour, Minute, Second

Manipulating Time Series Data in R

ISO 8601

  • Time elements arranged largest-to-smallest
    • Year -> month -> day -> ...
    • 2022-06-04
    • 2022-06-04 = June 4th, 2022
  • Time elements separated by specific characters
    • Hyphens (-) between date elements
    • 2022-06-04
  • Ensures legibility and clarity
    • 2022-06-04 vs. 20220604
Manipulating Time Series Data in R

Formatting dates and times

lubridate::parse_date_time()

earthday <- "April 22, 2022"

parse_date_time(earthday,
                orders = "%B %d, %Y")
[1] "2022-08-22 UTC"

?strptime to view conversion specifications

Common conversion specifications:

Time Element Conversion Spec.
Year (YYYY) %Y
Year (yy) %y
Day (dd) %d
Month (mm) %m
Month (August) %B
Month (Aug) %b
Manipulating Time Series Data in R

Parsing multiple date formats

dates_vector <- c("12/20/2022",
                  "2022-12-21",
                  "December 22, 2022")
dates_vector
[1] "12/20/2022"
[2] "2022-12-21"
[3] "December 22, 2022"
library(lubridate)
parse_date_time(
  dates_vector,
  orders = c("%m/%d/%Y",
             "%Y-%m-%d",
             "%B %d, %Y"))
[1] "2022-12-20 UTC"
[2] "2022-12-21 UTC"
[3] "2022-12-22 UTC"
Manipulating Time Series Data in R

Let's practice

Manipulating Time Series Data in R

Preparing Video For Download...