1

I have date and time information in the following format:

z <- 20201019083000

I want to convert it into a readable date and time format such as follows:

"2020-10-19 20:20"

So far I have tried this but cannot get the correct answer.

#in local

as.POSIXct(z, origin = "1904-01-01")
"642048-10-22 14:43:20 KST"

#in UTC

as.POSIXct(z, origin = "1960-01-01", tz = "GMT")
"642104-10-23 05:43:20 GMT"

#in

 as.POSIXct(as.character(z), format = "%H%M%S")
    "2021-07-13 20:20:10 KST"

Any better way to do it?

2 Answers2

2
library(lubridate)
ymd_hms("20201019083000")
# [1] "2020-10-19 08:30:00 UTC"

# or, format the output:
format(ymd_hms("20201019083000"), "%Y-%m-%d %H:%M")
# "2020-10-19 08:30"
heds1
  • 3,203
  • 2
  • 17
  • 32
2

You can use as.POSIXct or strptime with the format %Y%m%d%H%M%S:

as.POSIXct(as.character(z), format="%Y%m%d%H%M%S")
#[1] "2020-10-19 08:30:00 CEST"

strptime(z, "%Y%m%d%H%M%S")
#[1] "2020-10-19 08:30:00 CEST"

Your tried format "%H%M%S" dos not include Year %Y , Month %m and Day %d.

GKi
  • 37,245
  • 2
  • 26
  • 48