Formatting a date in R without leading zeros

22.6k Views Asked by At

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.

4

There are 4 best solutions below

5
G. Grothendieck On BEST ANSWER

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.

1
Liang Zhang On

I have discovered a workaround by using year(), month() and day() function of {lubridate} package. With the help of glue::glue(), it is easy to do it as following:

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
library(glue)
dt <- "1998-09-02"
glue("{year(dt)}, {month(dt)}, {day(dt)}")
#> 1998, 9, 2

Created on 2021-04-19 by the reprex package (v2.0.0)

Edit on 2023-03-02:

After {tidyverse} 2.0.0, {lubridate} is attached after attaching {tidyverse}, so there is no need to attach {lubridate} now:

library(tidyverse)
dt <- "1998-09-02"
str_glue("{year(dt)}, {month(dt)}, {day(dt)}")
#> 1998, 9, 2

Created on 2023-03-02 with reprex v2.0.2

If {tidyverse} is used (suggested by @banbh), then str_glue() can be used:

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
dt <- "1998-09-02"
str_glue("{year(dt)}, {month(dt)}, {day(dt)}")
#> 1998, 9, 2

Created on 2021-04-19 by the reprex package (v2.0.0)

5
RyanFrost On

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"
0
user3799203 On

A more general solution using gsub, to remove leading zeros from the day or month digits produced by %m or %d. This deletes any zero that is not preceded by a digit:

gsub("(\\D)0", "\\1", format(as.Date("1998-09-02"), "%Y, %m, %d"))