Explain with examples how to use timestamps in R.
R gives us a variety of tools for working with timestamp information. Let's start off by exploring the Date object:
We can use the as.Date() function to convert a character string to a Date object, which will allow it to contain more time information. The string will need to be in a standard time format. We can ask for today's date by asking the system (Sys.) for the Date:
Sys.Date()
[1] "2020-01-26"
Let's show some examples of how to use as.Date and the format argument for this:
# YYYY-MM-DD
as.Date('1990-11-03')
[1] "1990-11-03"
# Using Format
as.Date("Nov-03-90",format="%b-%d-%y")
[1] "1990-11-03"
# Using Format
as.Date("November-03-1990",format="%B-%d-%Y")
[1] "1990-11-03"
as.POSIXct("11:02:03",format="%H:%M:%S")
[1] "2016-05-12 11:02:03 PDT"
as.POSIXct("November-03-1990 11:02:03",format="%B-%d-%Y %H:%M:%S")
[1] "1990-11-03 11:02:03 PST"
Most times, we'll actually be using the strptime() function, instead of POSIXct. Here's a quick lowdown on the differences between the functions:
There's two internal implementations of date/time: POSIXct, which stores seconds since UNIX epoch (+some other data), and POSIXlt, which stores a list of day, month, year, hour, minute, second, etc.
strptime is a function to directly convert character vectors (of a variety of formats) to POSIXlt format.
as.POSIXlt converts a variety of data types to POSIXlt. It tries to be intelligent and do the sensible thing - in the case of character, it acts as a wrapper to strptime.
as.POSIXct converts a variety of data types to POSIXct. It also tries to be intelligent and do the sensible thing - in the case of character, it runs strptime first, then does the conversion from POSIXlt to POSIXct.
Let us see how strptime works
strptime("11:02:03",format="%H:%M:%S")
[1] "2016-05-12 11:02:03 PDT"