Dates in R


Dates are represented as the number of days since 1970-01-01, with negative values for earlier dates.

# use as.Date( ) to convert strings to dates
mydates <- as.Date(c("2023-03-23", "2023-03-15"))
# number of days between 3/23/23 and 3/15/23
days <- mydates[1] - mydates[2]
days

# today's date - the default format is yyyy-mm-dd
Sys.Date( )

Time

What is difftime()? The difftime() function in R computes the difference between two objects of date or time.

# Creating date-time objects
time1 <- "2023-03-13 19:09:24"                
time2 <- "2023-03-12 19:09:24"  
# Calling the difftime() function where our result should be in unit hours
difftime(time1, time2, units="hours")

You can format dates. We can use whatever separators we like.

> #define date
> date <- as.Date("2023-03-27")
> date
[1] "2023-03-27"
> formatted_date <- format(date, format="%Y/%m/%d")
> formatted_date
[1] "2023/03/27"
> formatted_date <- format(date, format="%Y%m%d")
> formatted_date
[1] "20230327"
> formatted_date <- format(date, format="%A, %B %d %Y")
> formatted_date
[1] "Monday, March 27 2023"

Here’s an article called The Complete Guide to Date Formats in R.

There is also the abbreviated weekday as %a and the abbreviated month as %b.

For date time conversions have a look at the web page called as.POSIX*: Date-time Conversion Functions.

# some examples of date and time string manipulation
now_datetime <- str_replace(Sys.Date(),"-","")
now_datetime <- str_replace_all(now_datetime, "-", "")    # remove the -
now_datetime <- paste(now_datetime, format(as.POSIXct(Sys.time(), tz = "UTC"), "%H%M%S"))
now_datetime = str_replace(now_datetime, " ", "")
print(paste(now_datetime, "in format yyyymmddhhmmss", sep = ""))

Leave a Reply