Real-time research in ecology, economics, and sustainability

Today at the Davis R Users’ Group, Bonnie Dixon gave a tutorial on the various ways to handle dates and times in R. Bonnie provided this great script which walks through essential classes, functions, and packages. Here it is piped through knitr::spin. The original R script can be found as a gist here.

Date/time classes

Three date/time classes are built-in in R, Date, POSIXct, and POSIXlt.

Date

This is the class to use if you have only dates, but no times, in your data.

Lubridate distinguishes between four types of objects: instants, intervals, durations, and periods. An instant is a specific moment in time. Intervals, durations, and periods are all ways of recording time spans.

Dates and times parsed in lubridate are instants:

is.instant(tm1.lub)

## [1] TRUE

round an instant:

round_date(tm1.lub, "minute")

## [1] "2013-07-24 23:55:00 UTC"

round_date(tm1.lub, "day")

## [1] "2013-07-25 UTC"

get the current time or date as an instant:

now()

## [1] "2014-02-10 18:26:02 PST"

today()

## [1] "2014-02-10"

Note that lubridate uses UTC time zones as default.

see an instant in a different time zone:

with_tz(tm1.lub, "America/Los_Angeles")

## [1] "2013-07-24 16:55:26 PDT"

change the time zone of an instant (keeping the same clock time):

force_tz(tm1.lub, "America/Los_Angeles")

## [1] "2013-07-24 23:55:26 PDT"

some calculations with instants. Note that the units are seconds:

tm2.lub -tm1.lub

## Time difference of 8.611 hours

tm2.lub >tm1.lub

## [1] TRUE

tm1.lub +30

## [1] "2013-07-24 23:55:56 UTC"

An interval is the span of time that occurs between two specified instants.

An example of using times and dates in a data frame

Here is a data frame with a week of hypothetical times of going to bed and getting up for one person, and the total amount of time sleep time obtained each night according to a sleep monitoring device.