0

I have date&time stamp as a character variable

"2018-12-13 11:00:01 EST" "2018-10-23 22:00:01 EDT" "2018-11-03 14:15:00 EDT" "2018-10-04 19:30:00 EDT" "2018-11-10 17:15:31 EST" "2018-10-05 13:30:00 EDT"

How can I strip the time from this character vector?

PS: Can someone please help. I have tried using strptime but I am getting NA values as a result

zx8754
  • 52,746
  • 12
  • 114
  • 209
NMB
  • 35
  • 1
  • 4
  • You can try `sapply(strsplit(x, " "), function(x) x[2])`. – tmfmnk Mar 18 '19 at 16:56
  • this works! thanks. I have a follow up question: I get all the times in character format. how can I convert it to numeric or time format(?) so that I can find the number of views of a particular post at each hour of the day? – NMB Mar 18 '19 at 17:18
  • Your question is a bit unclear, do you want the output to be the date or the time? If date, see answers below. If time, see: https://stackoverflow.com/questions/50736661/extract-time-hms-from-lubridate-date-time-object – Shinobi_Atobe Mar 18 '19 at 17:59

4 Answers4

1

It's a bit unclear whether you want the date or time but if you want the date then as.Date ignores any junk after the date so:

x <- c("2018-12-13 11:00:01 EST", "2018-10-23 22:00:01 EDT")
as.Date(x)
## [1] "2018-12-13" "2018-10-23"

would be sufficient to get a Date vector from the input vector x. No packages are used.

If you want the time then:

read.table(text = x, as.is = TRUE)[[2]]
## [1] "11:00:01" "22:00:01"

If you want a data frame with each part in a separate column then:

read.table(text = x, as.is = TRUE, col.names = c("date", "time", "tz"))
##         date     time  tz
## 1 2018-12-13 11:00:01 EST
## 2 2018-10-23 22:00:01 EDT
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

I think the OP wants to extract the time from date-time variable (going by the title of the question).

x <- "2018-12-13 11:00:01 EST"

as.character(strptime(x, "%Y-%m-%d %H:%M:%S"), "%H:%M:%S")
[1] "11:00:01"

Another option:

library(lubridate)

format(ymd_hms(x, tz = "EST"), "%H:%M:%S")
[1] "11:00:01"
Debbie
  • 391
  • 2
  • 18
0

The package lubridate makes everything like this easy:

library(lubridate)

x <- "2018-12-13 11:00:01 EST"

as_date(ymd_hms(x))
Shinobi_Atobe
  • 1,793
  • 1
  • 18
  • 35
0

You can use the as.Date function and specify the format

> as.Date("2018-12-13 11:00:01 EST", format="%Y-%m-%d")
[1] "2018-12-13"

If all values are in a vector:

x = c("2018-12-13 11:00:01 EST", "2018-10-23 22:00:01 EDT", 
      "2018-11-03 14:15:00 EDT", "2018-10-04 19:30:00 EDT", 
      "2018-11-10 17:15:31 EST", "2018-10-05 13:30:00 EDT")

> as.Date(x, format="%Y-%m-%d")
[1] "2018-12-13" "2018-10-23" "2018-11-03" "2018-10-04" "2018-11-10"
[6] "2018-10-05"   
NM_
  • 1,887
  • 3
  • 12
  • 27