[R] Convert string to date time

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Wed Nov 27 07:34:19 CET 2024


Às 00:53 de 27/11/2024, Sorkin, John escreveu:
> I am reading a string that has the following form:
> 
> "2020-08-26_05:15:01"
> 
> I want to convert the string to a date-time variable. I tired:
> 
> x <- "2007-02-01_10:10:30"
> x <- as.POSIXct(x,tz=Sys.timezone())
> x
> 
> but this did not work; the time portion was ignored. I suspect the problem is the _ between the date and time, but I don't know how to account for this character in the string.
> 
> I hope someone can tell me how to read the string as a date time constant.
> 
> John
> 
> 
> 
> John David Sorkin M.D., Ph.D.
> Professor of Medicine, University of Maryland School of Medicine;
> Associate Director for Biostatistics and Informatics, Baltimore VA Medical Center Geriatrics Research, Education, and Clinical Center;
> PI Biostatistics and Informatics Core, University of Maryland School of Medicine Claude D. Pepper Older Americans Independence Center;
> Senior Statistician University of Maryland Center for Vascular Research;
> 
> Division of Gerontology and Paliative Care,
> 10 North Greene Street
> GRECC (BT/18/GR)
> Baltimore, MD 21201-1524
> Cell phone 443-418-5382
> 
> 
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Hello,

Pass an explicit format string with the underscore between the date and 
time parts.


x <- "2007-02-01_10:10:30"
as.POSIXct(x, format = "%Y-%m-%d_%H:%M:%S", tz = Sys.timezone())


Hope this helps,

Rui Barradas


-- 
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com



More information about the R-help mailing list