Question

A relatively simple question I hope. I'm trying to print out some dates in R but need the output to be in a specific format, with a single character for day, like: 2/10/2013

Here is an example of what I'm trying to do:

date_time <- as.POSIXct(paste("3/02/2012", "00:10:09", sep=" "), format="%d/%m/%Y %H:%M:%S")
print(format(date_time, "%d/%m/%Y %H:%M:%S"))

Which returns

"03/02/2012 00:10:09"

But what I want is to not have the leading 0, like so:

"3/02/2012 00:10:09"

Any idea how to format it this way? Note that for 2 digit days I still want both digits returned and for month I want 2 digits always.

ps. Yes, in Australia we format out dates dd/mm/yyyy

Was it helpful?

Solution

From ?strptime:

 ‘%e’ Day of the month as decimal number (1-31), with a leading
          space for a single-digit number.

so:

gsub("^ ", "" , format(date_time, "%e/%m/%Y %H:%M:%S"))
[1] "3/02/2012 00:10:09"

or

gsub("^0", "", format(date_time, "%d/%m/%Y %H:%M:%S"))
[1] "3/02/2012 00:10:09"

OTHER TIPS

picky, picky. Not sure if there is an easier way, but you could just write your own format function:

date_time <- as.POSIXct(paste("3/02/2012", "00:10:09", sep=" "), format="%d/%m/%Y %H:%M:%S")

format.date <- function(x, ...) {
  tmp <- format(x, ...)
  tmp <- sub("^[0]+", "", tmp)
  tmp <- sub('/0','/', tmp)
  return(tmp)
}

format.date(date_time, "%d/%m/%Y %H:%M:%S")
##  "3/2/2012 00:10:09"

Continuing from Jake's answer but without the regex, you can use stringr::str_squish to remove the leading space used by %e.

str_squish(format(date_time, "%e/%m/%Y %H:%M:%S"))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top