R Programming/Times and Dates
R contains a set of object types for holding date and time information. The system time and date can also be requested.
Format
Many time and date units are recognised. These include:
| Unit | Symbol | Example |
|---|---|---|
| 4 digit year | %Y | 1932 |
| 2 digit year | %y | 84 |
| Numerical Month | %m | 03 |
| Full Month | %B | January |
| Abbreviated Month | %b | Jan |
| Day of the month | %d | 31 |
| Full weekday | %A | Wednesday |
| Abbreviated weekday | %a | Wed |
| Hours (24hr clock) | %H | 16 |
| Minutes | %M | 35 |
| Seconds | %S | 52 |
The default format is yyyy-mm-dd hh:mm:ss or %Y-%m-%d %H:%M:%S
For example 2010-02-13 23:12:24
System Date and Time
To get the system date and time:
> Sys.time() [1] "2010-02-13 23:12:24 COT" > format(Sys.time(),"%H %M") # in a different format and without the date [1] "23 13" > Sys.date() [1] "2010-02-13" > date() # returns the current date and time, [1] "Wed Jul 18 10:59:42 2012"
Convert Strings to Date/Time Objects
Convert a string representing the date or time into a Date/Time object:
> my.date <- as.Date("2010-12-20") > print(my.date) [1] "2011-12-30" > my.date2 <- as.Date("12/20/10", format="%m/%d/%y") # input date in a different format > print(my.date2) [1] "2010-12-30" > my.time <- strptime("12/20/10 14.34.35", format="%m/%d/%y %H.%M.%S") # input time and date > print(my.time) [1] "2010-12-30 14:34:35" > my.string <- as.character(Sys.time()) # convert a date/time object to a normal string > print(my.string) [1] "2011-02-30 02:31:15"
Most Useful Utility Functions for Dates
Get weekday, month and an integer representing the number of days since the beginning of epoch:
> weekdays(my.date) # Get a string representing the weekday of the specified date [1] "Monday" > months(my.date) [1] "December" # Get the month as well > my.date [1] "2010-12-20" > julian(my.date) # Get the integer number of days since the beginning of epoch [1] 14963 attr(,"origin") [1] "1970-01-01"
External links
- Do more with dates and times in R with lubridate 1.1.0 (a sample chapter from the “R in Action” book)