Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with date format using the function as.POSIXct in R

Tags:

r

posixct

I'm working with a date format of YYYY-mm-ddTHH:MM:SS.000Z (2014-02-05T08:45:01.326Z) or that has a separator T that separates the date from the time, and time indicator Z or "Zulu time" (UTC). I'm trying to store the timestamp as a class POSIXct using the following function:

timestamp <- as.POSIXct(strptime(as.character(data$Time), tz = "UTC", "%Y-%m-%d %H:%M:%S"))

at the moment I'm getting NA's. If anyone has some advice on how I can incorporate the 'T' and 'Z' indicators in my conversion I will highly appreciate it.

like image 753
Carmen Avatar asked Feb 25 '14 09:02

Carmen


People also ask

How do I use the AS date function in R?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.

What is POSIXct format in R?

POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.

Is POSIXct a data type in R?

Time and Date Variables. The POSIXct data type is the number of seconds since the start of January 1, 1970. Negative numbers represent the number of seconds before this time, and positive numbers represent the number of seconds afterwards.

What is the difference between POSIXct and POSIXlt and as date?

There are two POSIX date/time classes, which differ in the way that the values are stored internally. The POSIXct class stores date/time values as the number of seconds since January 1, 1970, while the POSIXlt class stores them as a list with elements for second, minute, hour, day, month, and year, among others.


1 Answers

You can include the characters in your format string:

d <- "2014-02-05T08:45:01.326Z"
timestamp <- strptime(d, tz = "UTC", "%Y-%m-%dT%H:%M:%OSZ")

Note that here %OS is used instead of %S because you have fractional seconds.

like image 152
Karsten W. Avatar answered Sep 21 '22 11:09

Karsten W.