You are currently viewing Dates and Times in R with Examples

Times in R are represented by the POSIXct or POSIXlt class and Dates are represented by the Date class. The as.Date() function handles dates in R without time. This function takes the date as a String in the format YYYY-MM-DD or YYY/MM/DD and internally represents it as the number of days since 1970-01-01. And, Times are stored internally as the number of seconds since 1970-01-01.

In this article, I will explain how to work with Dates and Times in R Programming Language by creating Dates and Times, manipulating, formatting, date and time operations e.t.c.

Facts of Dates and Times in R

  • Dates are represented by the Date class.
  • Times are represented by the POSIXct or the POSIXlt class.
  • Dates are stored internally as an integer representing the number of days since 1970-01-01.
  • Times are stored internally as an integer representing the number of seconds since 1970-01-01.

Following are the Date formats that are used to specify the date, I will use these in the examples below.

CodeMeaningCodeMeaning
%aAbbreviated weekday%AFull weekday
%bAbbreviated month%BFull month
%cLocale-specific date and time%dDecimal date
%HDecimal hours (24 hour)%IDecimal hours (12 hour)
%jDecimal day of the year%mDecimal month
%MDecimal minute%pLocale-specific AM/PM
%SDecimal second%UDecimal week of the year (starting on Sunday)
%wDecimal Weekday (0=Sunday)%WDecimal week of the year (starting on Monday)
%xLocale-specific Date%XLocale-specific Time
%y2-digit year%Y4-digit year
%zOffset from GMT%ZTime zone (character)

1. Dates in R

The as.Date() function handles dates in R without time. This function takes the date as a String in the format YYYY-MM-DD or YYY/MM/DD and internally represents it as the number of days since 1970-01-01.

So Date 1970-01-01 stores as 0, 1970-01-02 stores as 1. Let’s check this with an example.

The default input format for Date consists of the year, followed by the month and day, separated by slashes or dashes.


# Date examples
x <- as.Date("1970-01-01")
y <- as.Date("1970-01-02")
print(x)
print(y)

Yields below output. Note that typeof(x) returns a double value. And, class(x) returns Date.

dates in r

To check the internal value of these dates, use the unclass() function.


# Check internal value of date
unclass(x)
unclass(y)

Yields below output.

1.1 Dates not in Standard Format

If your input dates are not in the standard format, you have the specify the format as shown below.


z <- as.Date("01/01/1970",format='%m/%d/%Y')
print(z)

2. Times in R

Times are stored internally as the number of seconds since 1970-01-01. Times in R are represented either by the POSIXct or the POSIXlt class. Let’s see with examples what each time class brings to us.

POSIXct stores the time as a large integer value whereas POSIXlt stores the time as a list of values with information like day, month, week, year e.t.c. If you wanted to get a specific value of time this comes in handy.

The default input format for POSIX dates consists of the year, followed by the month and day, separated by slashes or dashes; for time values, the date may be followed by white space and a time in the form hour:minutes:seconds or hour:minutes followed by timezone.

2.1 POSIXct Time Class

The as.POSIXct() function takes date and time as input and returns the time of the type class POSIXct, it internally represents the time as a large integer value. Use the unclass() to check the integer value.


# Using POSIXct
timect <- as.POSIXct("2022-11-08 22:14:35 PST")
print(timect)
class(timect)
unclass(timect)

Yields below output.

times in r

2.2 POSIXlt Time Class

The as.POSIXlt() function also takes the date and time as string format and returns a value of type class POSIXlt, it internally stores the values of data and time parts as a list which ideally contains day, week, month, year, hour, minute, and the second e.t.c. You can check these values by calling unclass().


# Using as.POSIXlt
timelt <- as.POSIXlt("2022-11-08 22:14:35 PST")
print(timelt)
class(timelt)
unclass(timelt)

Yields below output.

posixlt

3. Operations on Dates & Times in R

You can perform several mathematic operations like + and – on Dates & Times and you can do comparisons too like ==, >, < e.t.c. Following are some examples.

3.1 Subtract Dates in R

In the below example, I am subtracting the date from another date which results in differences in the number of days.


# Date Diff
dateDiff <- as.Date("2021-01-01") - as.Date("2020-01-01")
print(dateDiff)

# Output
# Time difference of 366 days

3.2 Subtract Times in R

Now let’s use subtract time from another time, the result would be in decimal value.


#Time Diff
x <- as.POSIXlt("2022-11-08 03:14:35 PST") 
y <- as.POSIXlt("2022-11-09 26:14:35 PST") 
timeDiff <- y - x
print(timeDiff)

# Output
# Time difference of 20.75694 hours

3.3 Extract Parts of Data & Time

Since POSIXlt stores the time as an array by representing all date fields, you can use $ operator on the object to get the values. The fields you can use are “sec“, “min“, “hour“, “mday“, “mon“, “year“, “wday“, “day“, “isdst“, “zone“, “gmtoff“.


# Date & Time Values
timelt$sec
timelt$wday

# Output
#[1] 35
#[1] 2

3.4 Add Days to Dates

By using the + operator let’s add some days to the Date.


# Add days to date
newDate <- as.Date("2021-01-01") + 3
print(newDate)

# Output
#[1] "2021-01-04"

4. Dates & Times Functions in R

Following are some of the Dates and Times functions in R.

4.1 Sys.time()

Sys.time() returns the current system date and time in the format “2022-11-09 20:05:17 PST” which is of type class “POSIXct” or “POSIXt


x <- Sys.time()
print(x)
class(x)

4.2 Find Internal Between Dates

If you have a vector of dates or times, you can use the diff() function to get the difference between dates. The result of the below example would be different between the first and second dates and the different between the second and third dates.


# Differences
datesVec <- as.Date(c("2020-04-21", "2021-06-30", "2021-11-04"))
diff(datesVec)

# Output
#Time differences in days
#[1] 435 127

4.3 Generate Sequence of Dates

By using seq() function you can generate the sequence of dates with the specified length. The below example generates 5 dates by month difference.


dateMonth <- seq(as.Date("2020-04-21"), length = 5, by = "month")
dateMonth

# Output
#[1] "2020-04-21" "2020-05-21" "2020-06-21" "2020-07-21" "2020-08-21"

4.4 Truncate Date & Time

The trunc() function is used to truncate the date and time values. The below examples demonstrate the truncation of days, months, and years.


#truncate
x <- as.POSIXlt("2022-11-08 03:14:35 PST") 
trunc(x, "mins")
trunc(x, "days")
trunc(x, "year")

# Output
[1] "2022-11-08 03:14:00 PST"
[1] "2022-11-08 PST"
[1] "2022-01-01 PST"

4.5 strptime()

If you have dates and times in R with a different than standard format use strptime() to convert it to POSIXlt class. This function takes a character vector that has dates and times and converts into to a POSIXlt object.


#strptime() function example
strDate <- c("11 April, 2022 09:30", "20 November, 2022 10:05")
x <- strptime(strDate, "%d %B, %Y %H:%M")
print(x)
class(x)

Yields below output.

times in r

5. Conclusion

In this article you have learned different ways to represent date and times in R. Dates are represented by the Date class and Times are represented by the POSIXct or the POSIXlt class. Dates are stored internally as an integer representing number of days since 1970-01-01 and Times are stored internally as an integer representing number of seconds since 1970-01-01.

You can find the complete example explained in this article at R GitHub Examples Project.

Related Articles

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium