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:

Output:

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

Example 2:

Output:

Example 3:

Output:

Example 4:

Find the difference between current system date and specified date:

Output:

Example 5:

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

Output:

Example 6:

Let’s create a sequence of dates:

Output:

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:

Output:

Example 2:

Output:

Example 3:

Specify the time zone:

Output:

Example 4:

Let’s see some example of POSIXlt:

Output:

Example 5:

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:

Output:

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:

Output:

Example 2:

Output:

Reference:
https://www.stat.berkeley.edu/~s133/dates.html