1

i've searched for threads about timestamp conversion in R, but could not figure this out. I need to convert time column into timestamp so R would read it as dates. When the cell has only date without time, there is no problem, but the current format (either with + or without it in the cell - R considers it as integer or factor). How do i convert it into timestamp?

thank you enter image description here

Dmitry Leykin
  • 485
  • 1
  • 7
  • 14
  • maybe remove the +, with something like that substr(t, 1, nchar(t)-1) and then convert to date – MLavoie Dec 20 '15 at 15:06
  • removal of + leaves me with 29/11/2014 15:23 instead of 29-11-2014 15:23... i'm missing the conversion to date and time part – Dmitry Leykin Dec 20 '15 at 15:13
  • 1
    When you say that it's viewing it as an integer or a factor, that leads me to believe that you're reading your data in without setting `stringsAsFactors = FALSE`. This might be why you can't convert it to a date. Otherwise, it should work fine if you pass a valid format argument to `as.Date` – tblznbits Dec 20 '15 at 15:13
  • 1
    Nope, you do *not* need to remove it. See the answer I just added. – Dirk Eddelbuettel Dec 20 '15 at 15:16
  • 1
    And, and for future reference please _don't include data as a screenshot_. See [this SO post for why](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Dirk Eddelbuettel Dec 20 '15 at 15:41

2 Answers2

4

You do not need to remove the +:

R> crappyinput <- c("2014-11-29 15:23:02+", "2014-11-29 15:38:36+", 
+                   "2014-11-29 15:52:49+")
R> pt <- strptime(crappyinput, "%Y-%m-%d %H:%M:%S")
R> pt
[1] "2014-11-29 15:23:02 CST" "2014-11-29 15:38:36 CST" "2014-11-29 15:52:49 CST"
R> 

It will simply be ignored as trailing garbage.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
1

would this work for you?

t <- c("2014-11-29 15:23:02+")
t <- substr(t, 1, nchar(t)-1)
t
[1] "2014-11-29 15:23:02"
t <- strptime(t, format="%Y-%m-%d")
str(t)
 POSIXlt[1:1], format: "2014-11-29"
MLavoie
  • 9,671
  • 41
  • 36
  • 56
  • You don't even have to remove the plus sign. `t <- as.Date("2014-11-29 15:23:02+", format = "%Y-%m-%d %H:%M:%S+")` produces the same outcome, although not with a class of `POSIXlt`. – tblznbits Dec 20 '15 at 15:15