2

I have dataset containing date and time in the following format:

datetime<- c(20210830102055, 20210830102312, 20210830102335)
cycle <- c(25, 30, 35)
df <- data.frame(datetime, cycle)
df 
     datetime cycle
1 2.021083e+13    25
2 2.021083e+13    30
3 2.021083e+13    35

I'm trying to convert datetime column into

datetime2<- c("2021-08-30 10:20:55", "2021-08-30 10:23:12", "2021-08-30 10:23:35")
df <- data.frame(datetime2, cycle)
df

            datetime2 cycle
1 2021-08-30 10:20:55    25
2 2021-08-30 10:23:12    30
3 2021-08-30 10:23:35    35

Any efficient way to do this?

Thanks

3 Answers3

2

You can use ymd_hms() in lubridate package:

datetime<- c(20210830102055, 20210830102312, 20210830102335)
cycle <- c(25, 30, 35)
df <- data.frame(datetime = ymd_hms(datetime), cycle)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2
datetime<- c(20210830102055, 20210830102312, 20210830102335)
cycle <- c(25, 30, 35)
df <- data.frame(datetime, cycle)

# METHOD 1
df$datetime <- as.POSIXct(as.character(df$datetime) , format = "%Y%m%d%H%M%S")

# METHOD 2

library(lubridate)
df$datetime <- ymd_hms(df$datetime)
Edison Wu
  • 47
  • 2
1

In Base R:

data.frame(datetime2=as.POSIXct(as.character(df$datetime),
                                format="%Y%m%d%H%M%S"), 
           cycle)

Output:

            datetime2 cycle
1 2021-08-30 10:20:55    25
2 2021-08-30 10:23:12    30
3 2021-08-30 10:23:35    35

The key here is as.POSIXct with format:

> as.POSIXct(as.character(df$datetime), format="%Y%m%d%H%M%S")
[1] "2021-08-30 10:20:55 CST" "2021-08-30 10:23:12 CST" "2021-08-30 10:23:35 CST"
>
U13-Forward
  • 69,221
  • 14
  • 89
  • 114