Home > Software design >  How to convert a text string 20200821144500 into date and time format in r?
How to convert a text string 20200821144500 into date and time format in r?

Time:07-09

I have a date/time column saved like this 20200821144500. How do I convert it to date and time format? I tried as.POSIXct('20200821144500',format="%Y-%m-%d %H:%M:%S") which returned NA. Am I using the wrong format or is there another way to do it?

CodePudding user response:

A possible solution, based on lubridate::ymd_hms:

lubridate::ymd_hms("20200821144500")  
  
#> [1] "2020-08-21 14:45:00 UTC"

CodePudding user response:

The main feature here is to tell which is first year month or day etc.. in the string. and to use HMS , because:

  • hms, hm and ms usage is defunct, please use HMS, HM or MS instead. Deprecated in version '1.5.6'.
library(lubridate)

string <- "20200821144500"

parse_date_time(string, "ymd_HMS")

[1] "2020-08-21 14:45:00 UTC"

CodePudding user response:

Another option using strptime with right format:

strptime(as.character(20200821144500),format="%Y%m%d%H%M%S")
#> [1] "2020-08-21 14:45:00 CEST"

Created on 2022-07-08 by the reprex package (v2.0.1)

  • Related