Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format 'day' as single digit in POSIXct date

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

like image 375
jprockbelly Avatar asked Dec 07 '25 02:12

jprockbelly


2 Answers

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"
like image 108
Jake Burkhead Avatar answered Dec 08 '25 15:12

Jake Burkhead


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"
like image 20
rawr Avatar answered Dec 08 '25 14:12

rawr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!