Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting datetime string to POSIXct date/time format in R

Consider a string in the format

test <- "YYYY-MM-DDT00:00:00.000-08:00"

My goal is to convert those strings to POSIXct format so that I can plot the data. my initial thought was to use

as.POSIXct(test)

...but that seems to truncate the datetime to just date. Any thoughts? The help info for as.POSIXct seems to imply that the input should be date and time separated by a space, not by a "T". Is this my issue?

like image 688
CFrench Avatar asked Feb 10 '14 00:02

CFrench


People also ask

How do I convert string to time in R?

To convert characters to time objects in R, use the strptime() function. To convert time objects to characters in R, use the strftime() function.

How do I convert a string to a Posix date in R?

To convert a string into date/time in R, call as. POSIXct() function and pass the string as argument to this function. We may optionally pass time zone, date/time format, etc., to this function. POSIXct class represents the calendar dates and times.

How do I change date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.


1 Answers

You need to specify a format for your conversion. Take a read of ?strptime to see all of the options for date formats.

#YYYY-MM-DDT00:00:00.000-08:00
test <- "2013-12-25T04:32:16.500-08:00"
z <- as.POSIXct(test,format="%Y-%m-%dT%H:%M:%OS")
op <- options(digits.secs = 3)
z
#[1] "2013-12-25 04:32:16.5 EST"
like image 83
thelatemail Avatar answered Oct 17 '22 15:10

thelatemail