The following are a few date and time functions that I needed to figure out early on when working with R.
We will start when we are… the current system date.
Notice that this function returns a Date object.
A string in this format is treated as a character unless cast to a Date type.
You can also pass in dates in other formats and cast them as strings by specifying the format in use.
To format date information in a wide variety of string formats, use the strftime function.
strftime(Sys.Date(),’%A: %B %d, %Y (Day %j of %Y)’)
This returns the string “Tuesday: June 15, 2010 (Day 166 of 2010)”
Dates can be manipulated arithmetically. To return the next ten days…
seq(Sys.Date(),Sys.Date() + 10,1)
…or the last ten days…
seq(Sys.Date(),Sys.Date() – 10,-1)
There are number of packages with special date and time functionality. For example, to find out the holidays for the New York Stock Exchange.
If you need a greater degree of time differentiation, the time (“POSIXlt” and “POSIXct”) is available as well.
Much more can be said about dates and times, particularly if you delve into time series plotting and analysis. Please comment on any additional date time functionality that you use in R.
If you are working with time series data, the timeSeries library provides some convenient functionality.
timeSequence(from=”2010-03-01″, to=”2010-03-03″, by=”day”)
timeSequence(from=”2010-03-01″, to=”2010-03-02″, by=”hour”)
The xts and zoo packages seem be the standard for time sequence plotting and analysis.