-2

I have a vector with a date as character

x <- "2015-02-01 09:05:23"

I want to convert it to a dateTime object

x <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")

and then "T" as separator between date and time (see XML Schema) to get the following output

"2015-02-01T09:05:23"

How do I get the "T" separator into the string?

feder80
  • 1,195
  • 3
  • 13
  • 34
  • What is `S`? Saturday or Sunday? If you add more details, `format(x, "%Y-%m-%d%a%H:%M:%S")` should work: `"2015-02-01Sun09:05:23"` –  Oct 28 '15 at 08:57
  • sorry, I had to edit my question! I am not looking for the weekday, but for a sperator – feder80 Oct 28 '15 at 09:04
  • 1
    Then `format(x, "%Y-%m-%dT%H:%M:%S")`: `"2015-02-01T09:05:23"` –  Oct 28 '15 at 09:04

3 Answers3

5

You can use format function to get a character object.

x <- "2015-02-01 09:05:23"  
format(as.POSIXct(x, "GMT"), "%FT%T")
#[1] "2015-02-01T09:05:23"
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
1
x <- "2015-02-01 09:05:23"
d <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")
w <- substr(weekdays(d),1,1) # 1,1 selects the first letter of the day

y <- paste0(strsplit(as.character(d)," ")[[1]][1],w,strsplit(as.character(d)," ")[[1]][2])

y
[1] "2015-02-01S09:05:23"

if you just want to write a T :

paste0(strsplit(as.character(d)," ")[[1]][1],'T',strsplit(as.character(d)," ")[[1]][2])

[1] "2015-02-01T09:05:23"
etienne
  • 3,648
  • 4
  • 23
  • 37
1

You can replace the space with T in this case using gsub

x <- "2015-02-01 09:05:23"
x <- as.POSIXct(strptime(x, "%Y-%m-%d %H:%M:%S"), tz = "GMT")
gsub(" ", "T", x)

#[1] "2015-02-01T09:05:23"

As per @Avinash Raj 's comment using only sub would be enough in this case.

sub(" ", "T", x)
#[1] "2015-02-01T09:05:23"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • @AvinashRaj yes, you are right. Didn't know the difference between the two. Googled it. Thanks. Updated the answer. – Ronak Shah Oct 28 '15 at 09:19