Working with dates and time in R

Dates and Time are important Data Types in R which you will encounter in your day to day life.

There are three Date classes available in R – Date, POSIXct, and POSIXlt.

Date class deals with only dates i.e., Day, Month and Year. While, POSIXct and POSIXlt deal with Dates along with time.

Before, we start working with Date and Time in R – Remember that any programming language stores Dates as time difference from a fixed origin time.

In R this origin is Mid Night of 1970-01-01.

So, 1970-01-02 will be stored as 1, 1970-01-11 will be stored as 10 in R.

Working with Dates in R

First, we will start with Date class and then include the time as well. Let's print today's system date-

## [1] "2016-06-20"

Default date format in R follows YYYY-MM-DD structure but it can be changed using format() function in R.

Let see how Sys.Date() is stored internally-

## [1] 16972

It means that today's date is 16,972 days after the origin date i.e. 1970-01-01.

Many a times we receive Dates in our dataset to be in Character or a Factor format. We need to convert them into a Date object in order to work with it properly.

as.Date() is the function which is used to convert objects into a Date class. This function takes following arguments:

  • x: Object that needs to be converted
  • format: A character string. If not specified, it will try “%Y-%m-%d” then “%Y/%m/%d” on the first non NA element
  • origin: Reference origin date
  • tz: Timezone

%Y, %m, %d etc. are the Date elements. The complete list can be found in the help page of strptime()

Here are the most frequently used conversion specifications

Element Definition
%d Represents day of the month
%m Represents month in numeric format (01-12)
%b Represents abbreviated month name (e.g., jan)
%B Represents full month name (e.g., January)
%y Represents year without century (e.g., 00-99)
%Y Represents year with century
%H Represents Hours (00-23)
%M Represents Minutes (00-59)
%S Represents Second (00-59)

Let see a few examples.

char_var<-c("2012 01 22","2013 02 02","1990 03 25","1985 05 27")
## [1] "2012 01 22" "2013 02 02" "1990 03 25" "1985 05 27"
## [1] "character"

char_var stores 4 character strings. Let's convert it to a date object

## Error in charToDate(x): character string is not in a standard unambiguous format

The produced error tells us that R couldn't identify the format of character string passed to it.

Let's try again but this time with passing a date format

date_var<-as.Date(char_var,format="%Y %m %d")
## [1] "2012-01-22" "2013-02-02" "1990-03-25" "1985-05-27"

In format we pass the exact structure of the string in which it is occuring. Let see few more examples.

as.Date("On the day of 16 March in the year of 2016",format="On the day of %d %b in the year of %Y")
## [1] "2016-03-16"
## [1] "2016-01-03"
## [1] "Date"
Extracting date elements

There are a few functions which let you extract basic elements out of a Date object. For example,if you want to extract weekday, month etc. out of a date you can do it directly using these functions

## [1] "Monday"
## [1] "June"

Another way is to use format() function to extract date elements as you wish. As the name suggests, format() function is used to format a Date object in a way we want.

Remember, this format() function is different from the format argument we used in as.Date() function

Let say we just want to extract year out of a date

## [1] "2016"

Just use the combination of specifications and format will return you the extracted and formatted date.

##Sequencing through Dates

Similar to sequence of integers or numeric values we can also create sequence of dates.

Let's first create two Date objects-

## [1] "2016-01-01"
## [1] "2016-01-10"

Let's get intermediate dates between dt1 and dt2

## [1] "2016-01-01" "2016-01-02" "2016-01-03" "2016-01-04" "2016-01-05"
## [6] "2016-01-06" "2016-01-07" "2016-01-08" "2016-01-09" "2016-01-10"

We can even take difference of 2 days instead of 1

## [1] "2016-01-01" "2016-01-03" "2016-01-05" "2016-01-07" "2016-01-09"

Let's get 10 week dates

seq(dt1,length.out = 10,by="1 week")
## [1] "2016-01-01" "2016-01-08" "2016-01-15" "2016-01-22" "2016-01-29"
## [6] "2016-02-05" "2016-02-12" "2016-02-19" "2016-02-26" "2016-03-04"

Working with Date & Time

Till now we were handling objects which had typical date components, i.e., day, month & year

Let see what will happen if we have Time component as well in our character string.

dt_tm <-"2016-02-10 11:34:45"
## [1] "2016-02-10 11:34:45"
## [1] "character"

In order to convert this character object to a Date object we will be using strptime() function which is very similar to as.Date() call

dt_tm_convert<-strptime(dt_tm,format="%Y-%m-%d %H:%M:%S")
## [1] "2016-02-10 11:34:45 IST"
## [1] "POSIXlt" "POSIXt"

Class of a timestamp is POSIXlt or POSIXt.

Class"POSIXct" is a signed number of seconds since the beginning of 1970 in the UTC timezone.

Whereas “POSIXlt” is a named list of vectors, which represets:

Field Meaning
sec 0-61: seconds
min 0-59: minutes
hour 0-23: hours
mday 1-31: day of the month
mon 0-11: months
year years since 1900
wday 0-6 day of the week, starting on Sunday
yday 0-365: day of the yea
isdst Daylight Saving Timeflag. Positive if in force, zero if not, negative if unknown
zone timezone
gmtoff The offset in seconds from GMT

Let see how doest it look for our object.

## sec min hour mday mon year wday yday isdst zone 
## "45" "34" "11" "10" "1" "116" "3" "40" "0" "IST" 
## gmtoff 
## NA

You can extract the information you want out of this list

## [1] 11
## [1] 116

The following two tabs change content below.


3 thoughts on “Working with dates and time in R

  • June 29, 2016 at 12:32 pm

    Hi littleRbook,
    i have vector date with multiple format so how can i get value in place of NA.please help me to do that.
    rdate rdate
    [1] “8-12-2015” “18-12-2015” “4/12/2015” “27-11-2015” “12/11/2015” “30-10-2015” “30-10-2015”
    [8] “30-10-2015”
    > rdate1 rdate1
    [1] “2015-12-08” “2015-12-18” NA “2015-11-27” NA “2015-10-30” “2015-10-30”
    [8] “2015-10-30”


Leave a Reply

Your email address will not be published. Required fields are marked *