Formatting a date in R without leading zeros

前端 未结 4 1589
野性不改
野性不改 2020-12-07 00:33

Is there a way to use the format function on a date object, specifically an object of class POSIXlt, POSIXct, or Date, wi

相关标签:
4条回答
  • 2020-12-07 00:57

    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 讨论(0)
  • 2020-12-07 00:59

    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"))
    
    0 讨论(0)
  • 2020-12-07 01:11

    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:

    require(lubridate)
    require(glue)
    dt <- "1998-09-02"
    glue("{year(dt)}, {month(dt)}, {day(dt)}")
    # 1998, 9, 2
    
    0 讨论(0)
  • 2020-12-07 01:22

    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.

    0 讨论(0)
提交回复
热议问题