Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

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"
>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading