Is there a way to use the format function on a date object, specifically an object of class POSIXlt, POSIXct, or Date, with the format %Y, %m, %d such that leading zeros are stripped from each of those 3 fields?
For example, I would like format(as.Date("1998-09-02"), "%Y, %m, %d") to return 1998, 9, 2 and not 1998, 09, 02.
To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.
The day of the month. Single-digit days will have a leading zero. The abbreviated name of the day of the week.
The default R date format is "yyyy-mm-dd". where "date" is "chr" type.
Just remove the leading zeros at the end:
gsub(" 0", " ", format(as.Date("1998-09-02"), "%Y, %m, %d")) ## [1] "1998, 9, 2" Use %e to obtain a leading space instead of a leading zero.
You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).
Insert a minus sign (-) before each term you'd like to remove leading zeros from:
format(as.Date("2020-06-02"), "%Y, %-m, %-d") [1] "2020, 6, 2" Insert a pound sign (#) before each desired term:
format(as.Date("2020-06-02"), "%Y, %#m, %#d") [1] "2020, 6, 2" If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With