as.Date, strptime

Format dates using the as.Date, or format dates with times using strptime. There are helpful defaults for as.Date.
as.Date(x, format="%Y-%m-%d")
  • x – A character vector of dates.
  • format – The format of the dates, using a percent symbols with characters to specify what types of date information can be found where. By default, the function will accept dates of the form "2012-02-26" or "2012/02/26", but this can be adjusted for other scenarios.
strptime(x, format)
  • x – A character vector of dates, possibly also including times.
  • format – The format of the dates, using a percent symbols with characters to specify what types of date and time information can be found where. See ?strptime for all of these character options and meanings.
For a complete list of the date/time specification options, see the help file for strptime.

Example. The first example uses the default formatting option for as.Date, the second uses an abbreviated year, and the third provides full date/time information (seconds can also be specified but are not included here). In each case, the date/time objects allow for differences to be computed, as shown here using the diff function.
> #=====> Simple Dates <=====#
> x <- c("2006-07-19", "2006-07-20", "2006-07-21",
+        "2006-07-22", "2006-07-23")
> d <- as.Date(x) # format="%Y-%m-%d"
> d
[1] "2006-07-19" "2006-07-20" "2006-07-21"
[4] "2006-07-22" "2006-07-23"
> 
> diff(d)
Time differences in days
[1] 1 1 1 1
> 
> 
> #=====> Abbreviated Years <=====#
> x <- c("06-07-19", "06-07-20", "06-07-21",
+        "06-07-22", "06-07-23")
> d <- as.Date(x, format="%y-%m-%d")
> d
[1] "2006-07-19" "2006-07-20" "2006-07-21"
[4] "2006-07-22" "2006-07-23"
> 
> diff(d)
Time differences in days
[1] 1 1 1 1
> 
> 
> #=====> Dates With Times <=====#
> x <- c("06-07-19, 5:12am", "06-07-20, 5:15am",
+        "06-07-21, 5:18pm", "06-07-22, 5:22am",
+        "06-07-23, 5:25am")
> d <- strptime(x, format="%y-%m-%d, %I:%M%p")
> d
[1] "2006-07-19 05:12:00" "2006-07-20 05:15:00"
[3] "2006-07-21 17:18:00" "2006-07-22 05:22:00"
[5] "2006-07-23 05:25:00"
> 
> diff(d)
Time differences in hours
[1] 24.05000 36.05000 12.06667 24.05000
attr(,"tzone")
[1] ""
> 
> 
> # Date/Time Formatting Options
> ?strptime

Leave a Reply