Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a date in R without leading zeros

Tags:

date

r

zero-pad

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.

like image 619
Jon Claus Avatar asked Aug 19 '14 15:08

Jon Claus


People also ask

How do I change date format in R?

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.

Should dates have leading zeros?

The day of the month. Single-digit days will have a leading zero. The abbreviated name of the day of the week.

What is the default format for date in R?

The default R date format is "yyyy-mm-dd". where "date" is "chr" type.


2 Answers

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.

like image 67
G. Grothendieck Avatar answered Oct 02 '22 15:10

G. Grothendieck


You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).

Unix

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" 

Windows

Insert a pound sign (#) before each desired term:

format(as.Date("2020-06-02"), "%Y, %#m, %#d") [1] "2020, 6, 2" 
like image 34
RyanFrost Avatar answered Oct 02 '22 13:10

RyanFrost