Getting datetimes into R
Just like dates without times, if you want R to recognize a string as a datetime you need to convert it, although now you use
as.POSIXct(). as.POSIXct() expects strings to be in the format YYYY-MM-DD HH:MM:SS.
The only tricky thing is that times will be interpreted in local time based on your machine's set up. You can check your timezone with Sys.timezone(). If you want the time to be interpreted in a different timezone, you just set the tz argument of as.POSIXct(). You'll learn more about time zones in Chapter 4.
In this exercise you'll input a couple of datetimes by hand and then see that read_csv() also handles datetimes automatically in a lot of cases.
This exercise is part of the course
Working with Dates and Times in R
Exercise instructions
- Use
as.POSIXct()and an appropriate string to input the datetime corresponding to Oct 1st 2010 at 12:12:00. - Enter the same datetime again, but now specify the timezone as
"America/Los_Angeles". - Use
read_csv()to read inrversions.csvagain. - Examine the structure of the
datetimecolumn to verifyread_csv()has correctly interpreted it as a datetime.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Use as.POSIXct to enter the datetime
as.POSIXct(___)
# Use as.POSIXct again but set the timezone to `"America/Los_Angeles"`
as.POSIXct(___, tz = ___)
# Use read_csv to import rversions.csv
releases <- read_csv(___)
# Examine structure of datetime column
str(___)