Specifying an order with `parse_date_time()`
What about if you have something in a really weird order like dym_msh
? There's no named function just for that order, but that is where parse_date_time()
comes in. parse_date_time()
takes an additional argument, orders
, where you can specify the order of the components in the date.
For example, to parse "2010 September 20th"
you could say parse_date_time("2010 September 20th", orders = "ymd")
and that would be equivalent to using the ymd()
function from the previous exercise.
One advantage of parse_date_time()
is that you can use more format characters. For example, you can specify weekday names with A
, I
for 12 hour time, am/pm indicators with p
and many others. You can see a whole list on the help page ?parse_date_time
.
Another big advantage is that you can specify a vector of orders, and that allows parsing of dates where multiple formats might be used.
You'll try it out in this exercise.
This exercise is part of the course
Working with Dates and Times in R
Exercise instructions
x
is a trickier datetime. Use the clues in the instructions to parsex
.two_orders
has two different orders, parse both by specifying the order to bec("mdy", "dmy")
.- Parse
short_dates
withorders = c("dOmY", "OmY", "Y")
. What happens to the dates that don't have months or days specified?
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Specify an order string to parse x
x <- "Monday June 1st 2010 at 4pm"
___(x, orders = "___")
# Specify order to include both "mdy" and "dmy"
two_orders <- c("October 7, 2001", "October 13, 2002", "April 13, 2003",
"17 April 2005", "23 April 2017")
parse_date_time(two_orders, orders = ___)
# Specify order to include "dOmY", "OmY" and "Y"
short_dates <- c("11 December 1282", "May 1372", "1253")
parse_date_time(short_dates, orders = ___)