📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

Dates and Times in R

R has developed a special representation for dates and times. Dates are represented by the Date class and times are represented by the POSIXct or the POSIXlt class. Dates are stored internally as the number of days since 1970-01-01 while times are stored internally as the number of seconds since 1970-01-01.

Dates in R:

Dates are represented by the Date class and we can get dates from a string of characters using the as.Date() function.

  • To get the Current Date use Sys.Date() function.

Example:

> x <- Sys.Date()
> print(x)
[1] "2025-03-05"
  • To get a ‘Date’ object from character.

Example:

> x <- as.Date("2025-01-01")
> print(x)
[1] "2025-01-01"
  • You can see the internal representation of a Date object by using the unclass() function.

Example:

> x <- as.Date("1970-01-03")
> print(unclass(x))
[1] 2

Times in R:

Times are represented by the POSIXct or the POSIXlt class. R uses POSIXct (compact, for calculations) and POSIXlt (list-like, for extraction of components).

  • To get the Current Date and Time use Sys.time() function.

Example:

> dt <- Sys.time()
> print(dt)
[1] "2025-03-10 21:03:46 IST"
> print(class(dt))
[1] "POSIXct" "POSIXt" 
  • Extracting Components using the POSIXlt object.

Example:

> # converting date object into POSIXlt object
> p_lt <- as.POSIXlt(dt)

> p_lt$year + 1900    # Year
[1] 2025

> p_lt$mon + 1        # Month (0-based index, so add 1)
[1] 3

> p_lt$mday           # Day of the month
[1] 10

> p_lt$hour           # Hour
[1] 21

> p_lt$min            # Minutes
[1] 3

> p_lt$sec            # Seconds
[1] 46.38
  • Arithmetic operations on Date and POSIXct objects.

Example:

> today_date <- Sys.Date()

> # Adding days
> next_week <- today_date + 7
> print(next_week)
[1] "2025-03-17"

> # Difference between dates
> days_diff <- as.Date("2025-04-01") - today_date
> print(days_diff)
Time difference of 22 days

Formatting Dates and Times

  • Use format() to display dates/times in different formats.

Example:

> format(today_date, "%B %d, %Y")
[1] "March 10, 2025"

> p_ct <- as.POSIXct("2025-03-10 14:30:00", tz = "UTC")
> format(p_ct, "%Y-%m-%d %H:%M:%S %Z")
[1] "2025-03-10 14:30:00 UTC"
CodeDescriptionExample
%Y4-digit year2025
%y2-digit year25
%mMonth (01-12)03
%dDay (01-31)10
%BFull month nameMarch
%bAbbreviated monthMar
%HHours (00-23)14
%MMinutes (00-59)30
%SSeconds (00-59)00
%ZTimezoneUTC