Sorath Abbasi
Sorath Abbasi

Reputation: 53

Converting YYYYMMDDHHMMSS to a date and time class in r

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

Upvotes: 2

Views: 1404

Answers (3)

Edison Wu
Edison Wu

Reputation: 47

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)

Upvotes: 2

Mincheol Shin
Mincheol Shin

Reputation: 51

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)

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71580

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"
>

Upvotes: 1

Related Questions