Abra
Abra

Reputation: 11

Parsing date and time using base R

x <- "15/06/2016 12:56:39" #where the format is dd/mm/Y and time
x <- as.POSIXct(strptime(x, format="%d/%m/%Y %H:%M:%OS"))

returns

"2016-06-15 12:56:39 CEST"

ignoring the format argument.

I tried passing strftime instead of strptime, but it throws an error about the string format being ambiguous.

How can I return a timestamp keeping the original format="%d/%m/%Y %H:%M:%OS" using base R?

I know I could use lubridate, but in my current environment I cannot import new libraries.

Upvotes: 1

Views: 369

Answers (3)

Uwe
Uwe

Reputation: 42544

I believe, this question has been asked many times before on SO.

I believe, there is a misunderstanding. You need to distinguish between

  • dates and date-times given as character strings,
  • the internal representation of dates and date-times as class Date and POSIXct or the like, and
  • the default formatting when objects of class Date or POSIXct or the like are printed.

The benefit of the internal representation is that you can do date or date-time arithmetic, resp., and that it sorts correctly.

You need format in two places:

  1. When coercing a character string to internal representation to tell where to look for the day, month, year, hours, minutes, and seconds information within the string and which characters to ignore.
  2. When coercing an internal representation to a character string, for instance when printing, to tell where to put the day, month, year, hours, minutes, and seconds information in the desired output.

By default, the ISO standard format (YYYY-MM-DD hh:mm:ss) is assumed in many places. The ISO format has the benefit that it is unambiguous and that it sorts well as character string.

Upvotes: 0

Cuong.S
Cuong.S

Reputation: 39

Are you looking for this?

 x <- "2016-06-15 12:56:39" 
 x <- as.POSIXct(strftime(x, format="%d/%m/%Y %H:%M:%OS"))

Upvotes: 0

amrrs
amrrs

Reputation: 6325

Just another format on top of that.

x <- "15/06/2016 12:56:39" #where the format is dd/mm/Y and time
format(strptime(x, format="%d/%m/%Y %H:%M:%OS"),"%d/%m/%Y %H:%M:%OS")

Upvotes: 1

Related Questions