Fryc
Fryc

Reputation: 143

how to convert the time format of a dataframe

I have this dataframe:

structure(list(time = structure(c(1177345800, 1177408800, 1177410600, 
1177412400, 1177414200), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    open = c(148.09, 148.23, 148.03, 147.48, 147.51), high = c(148.12, 
    148.29, 148.04, 147.65, 147.78), low = c(148.05, 147.85, 
    147.38, 147.32, 147.43), close = c(148.06, 148.04, 147.48, 
    147.51, 147.77), volume = c(172700L, 8306934L, 21686377L, 
    10742987L, 6065554L)), row.names = c(NA, -5L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x000001a7a5941ef0>)

As you can see tha date and the time are unified in one column. I would like to separate them in two columns.

The last thing i would like is to transform the time format: from "16:30:00" to "16:30". I want to eliminate tha last ":00" for all the rows

Thank you

Upvotes: 0

Views: 46

Answers (2)

akrun
akrun

Reputation: 887078

We can also use .(

library(data.table)
df[, c('date', 'time') := .(as.Date(time), format(time, '%H:%M'))] 

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388962

Since you have data.table using data.table syntax :

library(data.table)
df[, c('date', 'time') := list(as.Date(time), format(time, '%H:%M'))]
df

#    time   open   high    low  close   volume       date
#1: 16:30 148.09 148.12 148.05 148.06   172700 2007-04-23
#2: 10:00 148.23 148.29 147.85 148.04  8306934 2007-04-24
#3: 10:30 148.03 148.04 147.38 147.48 21686377 2007-04-24
#4: 11:00 147.48 147.65 147.32 147.51 10742987 2007-04-24
#5: 11:30 147.51 147.78 147.43 147.77  6065554 2007-04-24

Upvotes: 1

Related Questions