0

I have the following data frame,the data set is already imported from a database table and created_at column has character type:

sale_id      created_at
1               2016-05-28T05:53:31.042Z
2               2016-05-30T12:50:58.184Z
3               2016-05-23T10:22:18.858Z
4               2016-05-27T09:20:15.158Z
5               2016-05-21T08:30:17.337Z
6               2016-05-28T07:41:14.361Z

How can i extract only hour and minute from created_at column , preferably using base r libraries? i need to paste hour and minute together later and put it as a new column.

chessosapiens
  • 3,159
  • 10
  • 36
  • 58
  • 1
    `substr(df$created_at, 12, 16)` or if you don't need the `:` then `gsub(substr(df$created_at, 12, 16))` – hrbrmstr Jul 04 '16 at 12:15

2 Answers2

6

We can use the convenient functions in lubridate to convert the character column to DateTime and extract the hour and minute with format

library(lubridate)
v1 <- ymd_hms("2016-05-28T05:53:31.042Z")
format(v1, "%H:%M")
#[1] "05:53"

Or using only base R

format(as.POSIXct("2016-05-28T05:53:31.042z", format = "%Y-%m-%dT%H:%M:%S"),  "%H:%M")
#[1] "05:53"

Other options include with gsub

gsub(".*T|:\\d+\\..*", "", "2016-05-28T05:53:31.042z")
#[1] "05:53"
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Using only base R libraries:

format(as.POSIXct("2016-05-28T05:53:31.042z", format = "%Y-%m-%dT%H:%M:%S"),  "%H:%M")

05:31

It appears that's UTC format. For more details on parsing that format see this.

Let me show it using Sys.Date() for an example as well:

format(as.POSIXlt(Sys.time(), "America/New_York"), "%H:%M")

08:15

Using the infinitely better lubridate library:

require(lubridate)
minute(ymd_hms("2016-05-28T05:53:31.042Z"))

53

second(ymd_hms("2016-05-28T05:53:31.042Z"))

31.042

Community
  • 1
  • 1
Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • That's why i asked preferably base R packages – chessosapiens Jul 04 '16 at 12:11
  • @sanaz OK no problem, I have updated the question and will add a bit more to it as well – Hack-R Jul 04 '16 at 12:14
  • 1
    @sanaz Right that's why I was saying I didn't know what timezone it is but I would update it (and I added another example with Sys.Date). I figured out that it's GMT though and updated it again. – Hack-R Jul 04 '16 at 12:22