converting datetime string to POSIXct date/time format in R

49,350

You need to specify a format for your conversion. Take a read of ?strptime to see all of the options for date formats.

#YYYY-MM-DDT00:00:00.000-08:00
test <- "2013-12-25T04:32:16.500-08:00"
z <- as.POSIXct(test,format="%Y-%m-%dT%H:%M:%OS")
op <- options(digits.secs = 3)
z
#[1] "2013-12-25 04:32:16.5 EST"
Share:
49,350

Related videos on Youtube

CFrench
Author by

CFrench

Updated on July 09, 2022

Comments

  • CFrench
    CFrench almost 2 years

    Consider a string in the format

    test <- "YYYY-MM-DDT00:00:00.000-08:00"
    

    My goal is to convert those strings to POSIXct format so that I can plot the data. my initial thought was to use

    as.POSIXct(test)
    

    ...but that seems to truncate the datetime to just date. Any thoughts? The help info for as.POSIXct seems to imply that the input should be date and time separated by a space, not by a "T". Is this my issue?

    • Ista
      Ista over 10 years
      Since the XML extraction part works, and the question has nothing to do with that, I suggest editing the title of this question and removing the xml tag.
  • Dan
    Dan over 6 years
    Hey, thanks for your answer here. I have a Question too...chr [1:10000] "2016-05-30 23:39:51 UTC" "2016-05-30 23:52:34 UTC" is my data. So i get it to convert with as.POSIXct: as.POSIXct(df$event_ts_utc,format="%Y-%m-%d %H:%M:%OS") working fine, except for the TIMECODE "2016-05-30 23:39:51 CEST"! Any Ideas?
  • Dan
    Dan over 6 years
    did it! as.POSIXct(df$event_ts_utc,format="%Y-%m-%d %H:%M:%S", tz = "UTC")
  • stevec
    stevec about 4 years
    I had a slightly differently formatted date time stamp, so for me what worked was: as.POSIXct("2019-03-15 16:17:42" , format="%Y-%m-%d %H:%M:%OS")