R Date and Time

R provides very large range of capabilities to deal with times and dates. Generally, dates are internally stored as integers, and depending on the operations we will need, we could choose to do the same. R provides three date/time classes:

Date Class

This is the simplest data type. It handles with the date but does not deal with the times. The default format is “yyyy-mm-dd”. Internally Date object are stored as the number of days since 01-01-1970, using negative numbers for earlier dates.

Formats:

Code

Value

%d

Day of the month (decimal number)

%m

Month (decimal number)

%b

Month (abbreviated)

%B

Month (full name)

%y

Year (2 digit)

%Y

Year (4 digit)


Example 1:

#create a date
d <- as.Date("2019-03-11")
d

Output:

[1]  2019-03-11

If you are specifying non-standard format you must have to use format = argument.

Example 2:

# non –standard format must be specified
> d <- as.Date("03/11/2019", format = "%m/%d/%Y")
> d

Output:

[1]  2019-03-11

Example 3:

> d <- as.Date("March 11, 2019", format = "%B %d, %Y")
> d

Output:

[1] "2019-03-11"

Example 4:

Find the difference between current system date and specified date:

# take a difference
> Sys.Date() - as.Date("1970-01-01")

Output:

Time difference of 9157 days

Example 5:

> difftime(Sys.Date(), as.Date("1994-02-13"), units = "weeks")

Here, units argument can be “auto”, “secs”, “mins”, “hours”, “days”, “weeks”.

Output:

Time difference of 1308.143 weeks

Example 6:

Let's create a sequence of dates:

six.weeks <- seq(d, length = 6, by = "week")
six.weeks

Output:

[1] "2019-03-11" "2019-03-18" "2019-03-25" "2019-04-01" "2019-04-08" "2019-04-15"


POSIX

POSIX represents a portable operating system interface, primarily for UNIX, but available on another operating systems as well. Dates stored in the POSIX format are date/time values and also allows modification of time zone.

There are two POSIX types, i.e. POSIXct and POSIXlt. “ct” stands for calendar time, it stores the number of seconds since the origin (1 January, 1970). Negative numbers represents the number of seconds before this time and positive number represent the number of seconds afterwards.

And “lt” stands for local time. It keeps the date as a list of time attributes (such as “hour” and “mon”).

Code

Meaning

Code

Meaning

%a

Abbreviated weekday

%A

Full weekday

%b

Abbreviated month

%B

Full month

%c

Locale-specific date and time

%d

Decimal date

%H

Decimal hours (24 hour)

%I

Decimal hours (12 hour)

%j

Decimal day of the year

%m

Decimal month

%M

Decimal minute

%p

Locale-specific AM/PM

%S

Decimal second

%U

Decimal week of the year (starting on Sunday)

%w

Decimal Weekday (0=Sunday)

%W

Decimal week of the year (starting on Monday)

%x

Locale-specific Date

%X

Locale-specific Time

%y

2-digit year

%Y

4-digit year

%z

Offset from GMT

%Z

Time zone (character)


Example 1:

tm1 <- as.POSIXct("2019-03-11 23:55:26")
tm1

Output:

[1] "2019-03-11 23:55:26 IST"

Example 2:

tm2 <- as.POSIXct("24032019 08:32:07", format = "%d%m%Y %H:%M:%S")
tm2

Output:

[1] "2019-03-24 08:32:07 IST"

Example 3:

Specify the time zone:

tm3 <- as.POSIXct("1989-06-24 11:42:03", tz = "GMT")
tm3

Output:

[1] "1989-06-24 11:42:03 GMT"

Example 4:

Let's see some example of POSIXlt:

tm1.lt <- as.POSIXlt("1989-06-24 23:55:26")
tm1.lt

Output:

[1] "1989-06-24 23:55:26 IST"

Example 5:

unclass(tm1.lt)

Output:

$sec

[1] 26

$min

[1] 55

$hour

[1] 23

$mday

[1] 24

$mon

[1] 5

$year

[1] 89

$wday

[1] 6

$yday

[1] 174

$isdst

[1] 0

$zone

[1] "IST"

$gmtoff

[1] NA

Example 6:

unlist(tm1.lt)

Output:

sec    min   hour   mday    mon   year   wday   yday  isdst   zone   gmtoff
"26"   "55"   "23"   "24"     "5"     "89"    "6"     "174"    "0"   "IST"     NA


Chron Package

Chron is short for chronological. This package is good option when you don’t need to deal with time zones.

Chron is a package and it is not a base package, you will have to install it.

Example:

tm1.c <- as.chron("2019-06-24 23:55:26")
tm1.c

Output:

[1] (06/24/19 23:55:26)

Example 2:

tm2.c <- as.chron("06/24/13 08:32:07", "%m/%d/%y %H:%M:%S")
tm2.c

Output:

[1] (06/24/19 08:32:07)
Reference: https://www.stat.berkeley.edu/~s133/dates.html

Related Topics

First R Program

First  Hello World R Program As a convention, our first R program will be the “Hello World!” program. We can run our R program either at R command prompt or we...

3 minutes read.

Logistic Regression in R Programming

Logistic Regression is a classification supervised machine learning algorithm in R programming. Logistic Regression can also be termed Binomial Logistic Regression, Binary Logistic Regression, or Logit Model. Logistic Regression is...

4 minutes read.

Decision Tree in R Programming

The decision tree uses the branching method to show every possible output for the specific input. We can draw a decision tree by hand or create it using specialized software...

2 minutes read.

Pie Charts in R Programming

R programming has various libraries to plot various types of charts and graphs. A pie chart is a circular statistical chart or graph, which is divided into slices to represent the numerical...

4 minutes read.

Various types of Charts in R Programming

As we know, R Language is mostly used for analyzing the data and statistics purposes to represent our data graphically & pictorially in R studio. Charts and graphs are plotted in...

4 minutes read.

Clustering in R Programming

The clustering technique is an unsupervised machine learning in R programming. Before discussing clustering techniques, let's have a look at what unsupervised machine learning is?  Unsupervised learning is training the model with...

3 minutes read.

R Operators

A symbol that tells the compiler to perform specific mathematical or logical operations is called operator. R language supports mainly 5 different types of operators, which are listed below: Arithmetic...

3 minutes read.

How to create Histograms in R

R Histograms A Histogram is the graphical representation of the distribution of numeric data. It takes only one numeric variable as input. The variable is cut into several bars (also called...

2 minutes read.

R Excel Files

Microsoft Excel is the spreadsheet program which stores data in the .xls and .xlsx format. R has the facility to read directly from these files using some excel specific packages....

2 minutes read.

R Data Types

Data types are used to define the size and type of the variable. In R, there is no need to declare a variable as some data types. The variables are...

4 minutes read.

R JSON File

JSON stands for JavaScript Object Notation. It is a lightweight format for storing and transporting data. JSON file is often used when data is sent from a server to a...

2 minutes read.

R Inheritance

One the main concept of object oriented programming is inheritance which allows us to define a new class of existing classes. This means that we can derive new classes from...

5 minutes read.

R Pie Charts

R programming language provides many numbers of libraries to create charts and graphs. A pie-chart is a representation of data as slices of a circle with different colors representing counts...

2 minutes read.

Measures of Central Tendency in R Programming

Central Tendency or CT is one of the features of descriptive statistics. The Central tendency will let us know how the various groups of data are clustered around the central...

4 minutes read.

R If Else Statement

If statement It is the most simple decision-making statement. It checks the condition if the condition is true then only it will execute the block of statements written in the ‘if...

2 minutes read.

Scatter Plot in R Programming

A Scatter plot is a type of dispersion graph built to represent the various data points of variables. A Scatter plot is also known as a scatter graph or scattergram.  A scatter plot is used...

4 minutes read.

Poisson Distribution in R Programming

Poisson distribution is a type of distribution that deals with the probability distribution of the data values by taking the mean into consideration. Poisson distribution will estimate the probability value for...

3 minutes read.

R Line Graphs

Line graph or line chart is a graph that connects a series of points by drawing segments between them. A line graph represents the relationship between 2 variables. These points...

2 minutes read.

R Functions

In programming, a function is a group of instructions that you want to use repeatedly, because of their complexity, are better self-contained in sub-program and called when needed. Hence, we can...

4 minutes read.

Introduction to R Programming

What is R Programming? R is a programming language which provides an environment for software used for statistical analysis, graphics representation and reporting. It possesses an extensive catalog of...

4 minutes read.