How to parse dates and times with 00 minutes and 00 seconds in r?

I have a large dataset with dates and times as a 16-digit (in the form yyyymmddhhmmssss or 2005031600003000) character string.

I have written the following parsing command (dropping the last 2 digits from the string):

DATA[, 1 ] <- substr(DATA[, 1 ], 1, 14)
DATA[, 1 ] <- ymd_hms(DATA[, 1 ], quiet = FALSE)

The parsing works fine except for times with 00 minutes and 00 seconds (for example 2005030507000000) which fail to parse.

Is there a fix to this problem? parse_date_time command has exactly the same problem.

Upvotes: 3

Views: 396

Answers (1)

markus
markus

Reputation: 26343

Try as.POSIXct and pass the last two zeros to format

x <- c("2005031600003000", "2005030507000000")
as.POSIXct(x, format = "%Y%m%d%H%M%S00")
# [1] "2005-03-16 00:00:30 CET" "2005-03-05 07:00:00 CET"

From ?strptime

%H : Hours as decimal number (00–23) ...

%M : Minute as decimal number (00–59)

%S : Second as integer (00–61) ...

Upvotes: 3

Related Questions